package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.characteristic.TrackCharacteristic;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.excelEntity.ScoreDataDetailExcel;
import com.xmy.cultivate.entity.excelEntity.ScoreDataDetailExcellentExcel;
import com.xmy.cultivate.entity.excelEntity.ScoreDataDetailPassExcel;
import com.xmy.cultivate.entity.excelEntity.StudentScoreExcel;
import com.xmy.cultivate.entity.views.*;
import com.xmy.cultivate.enums.SourseLeveEnum;
import com.xmy.cultivate.excel.CourseSchedulingDetailExcel;
import com.xmy.cultivate.excel.ReturnPremiumDailySheet;
import com.xmy.cultivate.excel.StudentGradeExcel;
import com.xmy.cultivate.excel.StudentRosterExcel;
import com.xmy.cultivate.mapper.CourseSchedulingAlwaysMapper;
import com.xmy.cultivate.mapper.GradeMapper;
import com.xmy.cultivate.mapper.OrderDetailMapper;
import com.xmy.cultivate.mapper.TrackMarketMapper;
import com.xmy.cultivate.respons.ClassesNum;
import com.xmy.cultivate.respons.SchedulingGrade;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * <表格导出>
 * 导出Excel 前端控制器
 * </表格导出>
 *
 * @author heLin
 * @since 2023-09-23
 */
@RestController
@Scope("prototype")
@RequestMapping("/api/excel")
public class ExcelController extends BaseController {
    @Autowired
    IGradeService iGradeService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    IDictService iDictService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IStudentAccountService iStudentAccountService;

    @Autowired
    ICourseSchedulingService iCourseSchedulingService;

    @Autowired
    ITranscriptService iTranscriptService;

    @Autowired
    @Lazy
    IServiceFeedbackService iServiceFeedbackService;

    @Autowired
    CourseSchedulingAlwaysMapper courseSchedulingAlwaysMapper;

    @Autowired
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    IRepairCourseService iRepairCourseService;

    @Autowired
    IEnrollCustomerService iEnrollCustomerService;

    @Autowired
    IEnrollDataService iEnrollDataService;

    @Autowired
    IEnrollCommunicateService iEnrollCommunicateService;

    @Autowired
    IRepairCourseService iRepairCourseServicel;

    @Autowired
    IStaffRankingDetailService iStaffRankingDetailService;

    @Autowired
    IRoleService iRoleService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IStaffDataService iStaffDataService;

    @Autowired
    IQuarterService quarterService;

    @Autowired
    IRenewClassService iRenewClassService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    IOrderApplyService iOrderApplyService;

    @Autowired
    IStoreGoodsOrderBatchService iStoreGoodsOrderBatchService;

    @Autowired
    IStoreGoodsService iStoreGoodsService;

    @Autowired
    IStoreGoodsBatchService iStoreGoodsBatchService;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    TrackMarketMapper trackMarketMapper;

    @Resource
    TrackCharacteristic trackCharacteristic;

    @Autowired
    IGradeLayerService iGradeLayerService;

    @Autowired
    IRoleAdminService iRoleAdminService;


    @GetMapping("/gradeExcel")
    @ApiOperation("班级导出")
    public Result gradeExcel(
            @RequestParam Map<String, String> reMap,
            @RequestParam(value = "keyType", defaultValue = "1") String keyType,
            @RequestParam(value = "schoolIdList", defaultValue = "") String schoolId,
            @RequestParam(value = "classRoomIdList", defaultValue = "") String classRoomId,
            @RequestParam(value = "courseIdList", defaultValue = "") String courseId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNumList", defaultValue = "") String quarterNum,
            @RequestParam(value = "yearClassIdList", defaultValue = "") String yearClassId,
            @RequestParam(value = "isCheckHouse", defaultValue = "") String isCheckHouse,
            @RequestParam(value = "lessonType", defaultValue = "") String lessonType) {
        Page<Grade> page = new Page<>(-1, -1);
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        String name = reMap.get("name");//名称
        String subjectsId = reMap.get("subjectsId");
        String status = reMap.get("status");
        String gradeIdList = reMap.get("gradeIdList");//批量导出
        String teacherId = reMap.get("teacherId");

        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (StringUtils.isBlank(yearPart)) {
            yearPart = quarterNow.getYearPart().toString();
        }
        if (StringUtils.isBlank(quarterNum)) {
            quarterNum = quarterNow.getNum().toString();
        }
        String isScheduling = reMap.get("isScheduling");//是否排课

        if (StringUtils.isBlank(schoolId)) {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        if (StringUtils.isNotBlank(keyType)) {
            if (keyType == "3") {
                //课程
                queryWrapper.inSql(StringUtils.isNotBlank(name), "course_id", "select * from course where name like '%" + name + "%' ");
            } else if (keyType == "2") {
                //班主任
                queryWrapper.inSql(StringUtils.isNotBlank(name), "teacher_id", "select * from staff where name like '%" + name + "%' ");
            } else {
                queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
            }
        }

        if (StringUtils.isNotBlank(isScheduling)) {
            if (isScheduling.equals("1")) {
                queryWrapper.inSql("id", "select grade_id from course_scheduling where deleted=0 GROUP BY grade_id");
            } else {
                queryWrapper.notInSql("id", "select grade_id from course_scheduling where deleted=0 GROUP BY grade_id");
            }
        }

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.eq(StringUtils.isNotBlank(classRoomId), "class_room_id", classRoomId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.inSql(StringUtils.isNotBlank(gradeIdList), "id", gradeIdList);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        if (StringUtils.isNotBlank(isCheckHouse)) {
            if (isCheckHouse.equals("0")) {
                queryWrapper.inSql("id", "select grade_id from student_grade where `quarter_num`=" + quarterNum + " and year_part = " + yearPart + " and status<>3 and is_check_house = 0 and deleted=0 GROUP BY grade_id");
            } else {
                queryWrapper.notInSql("id", "select grade_id from student_grade where `quarter_num`=" + quarterNum + " and year_part = " + yearPart + " and status<>3 and is_check_house = 0 and deleted=0 GROUP BY grade_id");
                queryWrapper.inSql("id", "select grade_id from student_grade where `quarter_num`=" + quarterNum + " and year_part = " + yearPart + " and status<>3 and deleted=0 GROUP BY grade_id");
            }
        }

        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("created_at");

        List<Grade> grades = iGradeService.findAll(page, queryWrapper).getRecords();

        for (Grade grade : grades) {
            if (grade.getCount() != null && grade.getFullCount() != null) {
                grade.setStudentNumber(grade.getCount() + "/" + grade.getAdvanceCount() + "/" + grade.getFullCount());
            }
            if (grade.getRecruitStatus() != null) {
                grade.setEnrollmentStatus(grade.getRecruitStatus().getValue());
            }
            if (grade.getTeacherObj() != null) {
                grade.setTeacherName(grade.getTeacherObj().getName());
            }
            if (grade.getCourseObj() != null) {
                grade.setCourseStr(grade.getCourseObj().getName());
            }
            if (grade.getStatus() != null) {
                grade.setFinishStatus(grade.getStatus().getValue());
            }
            if (grade.getSchoolObj() != null) {
                grade.setSchoolName(grade.getSchoolObj().getName());
            }
            Grade gradeById = iGradeService.getById(grade.getId());
            if (gradeById != null) {
                if (gradeById.getIsScheduling() == 1) {
                    grade.setIsSchedulingStr("已排课");
                } else {
                    grade.setIsSchedulingStr("未排课");
                }
            } else {
                grade.setIsSchedulingStr("未排课");
            }
        }

        ExcelExportHandle.export(response, "班级明细", grades, Grade.class);
        return new Result(Code.OK, grades);
    }

    @ApiOperation("学员导出")
    @GetMapping("/studentExcel/{gradeId}")
    public Result getStudentByGradeIdExcel(@RequestParam Map<String, String> reMap, @PathVariable(value = "gradeId") Long gradeId) {
        Integer pageNum = -1;
        Integer pageSize = -1;

        String name = reMap.get("name");
        String studentList = reMap.get("studentList");
        String status = StringUtils.isEmpty(reMap.get("status")) ? "0" : reMap.get("status");// 0全部 1新生 2老生
        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");

        List<Long> roleIdList = iRoleAdminService.getRoleIdListForAdminId(this.adminId);
        // 判断是否为新老师
        Integer newTeacher = 0;
        Long teacherId = 0L;
        if (roleIdList != null && roleIdList.size() > 0) {
            for (Long roleId : roleIdList) {
                if (roleId.equals(1568160855895937096L)) {
                    newTeacher = 1;
                    break;
                }
            }
            Staff staff = iStaffService.getOneForAdminid(this.adminId);
            teacherId = staff.getId();
        }

        IPage<Student> gradeStudentList = iStudentService.getStudentForGradeId(gradeId, name, pageNum, pageSize, studentList, status, startDate, endDate, newTeacher, teacherId);

        for (Student student : gradeStudentList.getRecords()) {
            if (student.getAllCourseCount() == null) {
                student.setAllCourseCount(0);
            } else {
                student.setAllCourseCount(student.getAllCourseCount() / 3);
            }
            if (student.getUseCourseCount() == null) {
                student.setUseCourseCount(0);
            } else {
                student.setUseCourseCount(student.getUseCourseCount() / 3);
            }
            if (student.getResidueCourseCount() == null) {
                student.setResidueCourseCount(0);
            } else {
                student.setResidueCourseCount(student.getResidueCourseCount() / 3);
            }

            if (student.getArriveCount() == null) {
                student.setArriveCount(0);
            } else {
                student.setArriveCount(student.getArriveCount() / 3);
            }

            if (student.getRepairCount() == null) {
                student.setRepairCount(0);
            } else {
                student.setRepairCount(student.getRepairCount() / 3);
            }

            if (student.getIsCheckHouse() != null) {
                if (student.getIsCheckHouse() == 0) {
                    student.setIsCheckHouseStr("未核对");
                } else if (student.getIsCheckHouse() == 1) {
                    student.setIsCheckHouseStr("已核对");
                }
            }
            if (student.getCourseStatus() != null) {
                if (student.getCourseStatus() == 0) {
                    student.setCourseStatusStr("异常");
                } else if (student.getCourseStatus() == 1) {
                    student.setCourseStatusStr("正常");
                }
            }
            if (student.getSex() != null) {
                if (student.getSex() == 1) {
                    student.setSexStr("男");
                } else if (student.getSex() == 2) {
                    student.setSexStr("女");
                } else {
                    if (student.getSex() == 3) {
                        student.setSexStr("未知");
                    }
                }
            }
        }
        ExcelExportHandle.export(response, "班级学员", gradeStudentList.getRecords(), Student.class);
        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("排班表导出")
    @GetMapping("/gradeAndStudentExcel")
    public Result getStudentAndGradeIdExcelNew(@RequestParam Map<String, String> reMap, HttpServletResponse response) throws IOException {
        String schoolIdList = reMap.get("schoolIdList");
        String classRoomIdList = reMap.get("classRoomIdList");
        String courseIdList = reMap.get("courseIdList");
        String gradeIdList = reMap.get("gradeIdList");
        String yearClassIdList = reMap.get("yearClassIdList");
        String isCheckHouse = reMap.get("isCheckHouse");
        String lessonType = StringUtils.isEmpty(reMap.get("lessonType")) ? "1" : reMap.get("lessonType");
        String name = reMap.get("name");
        String subjectsId = reMap.get("subjectsId");
        String status = reMap.get("status");
        String teacherId = reMap.get("teacherId");
        String yearPart = reMap.get("yearPart");
        String quarterNumList = reMap.get("quarterNumList");

        Boolean isBeforehand = false;// 是否大于当前季度（是否为预分班格式）
        // 获取季度
        Quarter quarter = iQuarterService.getQuarterForYearAndNum(Integer.valueOf(yearPart), Integer.valueOf(quarterNumList));
        if (quarter.getStartDate().isAfter(LocalDate.now())) {
            isBeforehand = true;
        }

        List<StudentGradeExcel> workingSchedule = new ArrayList<>();
        if (isBeforehand) {
            workingSchedule = iGradeService.workingScheduleBeforehandNew(schoolIdList, name, yearClassIdList, subjectsId, status, classRoomIdList, courseIdList, yearPart, quarterNumList, teacherId, isCheckHouse, lessonType, gradeIdList);
        } else {
            workingSchedule = iGradeService.workingScheduleNew(schoolIdList, name, yearClassIdList, subjectsId, status, classRoomIdList, courseIdList, yearPart, quarterNumList, teacherId, isCheckHouse, lessonType, gradeIdList);
        }

        CellRangeAddress cellRangeAddress = CellRangeAddress.valueOf("A1:P1");
        List<String> headList = new ArrayList<>();
        headList.add("班级名称");
        headList.add("开班校区");
        headList.add("班型");
        headList.add("学员姓名");
        headList.add("关系");
        headList.add("联系方式");

        if (isBeforehand) {
            headList.add("通关数");
            headList.add("正确率");
            headList.add("期中分数");
            cellRangeAddress = CellRangeAddress.valueOf("A1:I1");
        } else {
            headList.add("总课次");
            headList.add("剩余课次");
            headList.add("已用课次");
            headList.add("到课数量");
            headList.add("请假数量");
            headList.add("报读科目");
            headList.add("报读校区");
            headList.add("亲属姓名");
            headList.add("亲属报读科目");
            headList.add("亲属报读校区");
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("排班表");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();// 创建字体对象
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 16);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
        headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(30);
        sheet.createFreezePane(0, 1);// 冻结首行
        headerCellStyle.setFont(headerFont);
        sheet.setAutoFilter(cellRangeAddress);

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 13);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFont(font);
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));

        int rowIndex = 1; // 数据行起始索引
        String lastGradeExcel = null; // 上一个班级名称
        String lastStudentName = null; // 上一个学生姓名
        int lastStudentNameRowIndex = 1; // 上一个学生姓名的数据行索引，初始化为1
        int lastGradeNameRowIndex = 1; // 上一个班级姓名的数据行索引，初始化为1

        if (isBeforehand) {
            for (StudentGradeExcel studentGradeExcel : workingSchedule) {
                Row row = sheet.createRow(rowIndex);

                Cell cell = row.createCell(0);
                cell.setCellValue(studentGradeExcel.getGradeName());
                sheet.setColumnWidth(0, 30 * 256);
                cell.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(studentGradeExcel.getOpenClassSchoolName());
                sheet.setColumnWidth(1, 20 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(studentGradeExcel.getClassTypeName());
                sheet.setColumnWidth(2, 20 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(3);
                cell3.setCellValue(studentGradeExcel.getStudentName());
                sheet.setColumnWidth(3, 20 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(studentGradeExcel.getLinkman());
                sheet.setColumnWidth(4, 20 * 256);
                cell4.setCellStyle(cellStyle);

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(studentGradeExcel.getLinkmanPhone());
                sheet.setColumnWidth(5, 25 * 256);
                cell5.setCellStyle(cellStyle);

                Cell cell6 = row.createCell(6);
                if (studentGradeExcel.getPassShutNum() != null) {
                    cell6.setCellValue(studentGradeExcel.getPassShutNum());
                }
                sheet.setColumnWidth(6, 25 * 256);
                cell6.setCellStyle(cellStyle);

                Cell cell7 = row.createCell(7);
                if (studentGradeExcel.getRightRade() != null) {
                    cell7.setCellValue(studentGradeExcel.getRightRade() + "%");
                }
                sheet.setColumnWidth(7, 25 * 256);
                cell7.setCellStyle(cellStyle);

                Cell cell8 = row.createCell(8);
                if (studentGradeExcel.getMidtermScore() != null) {
                    cell8.setCellValue(studentGradeExcel.getMidtermScore());
                }
                sheet.setColumnWidth(8, 25 * 256);
                cell8.setCellStyle(cellStyle);

                // 班级名称~班型合并逻辑
                if (lastGradeExcel != null && !studentGradeExcel.getGradeName().equals(lastGradeExcel)) {
                    if (rowIndex - lastGradeNameRowIndex > 1) {
                        for (int j = 0; j <= 2; j++) {
                            sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, j, j));
                        }
                    }
                    lastGradeNameRowIndex = rowIndex; // 更新为当前数据行索引
                }
                lastGradeExcel = studentGradeExcel.getGradeName();

                rowIndex++;
            }

            // 处理最后一个班级的合并
            if (rowIndex - lastGradeNameRowIndex > 1) {
                for (int j = 0; j <= 2; j++) {
                    sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, j, j));
                }
            }

        } else {
            for (StudentGradeExcel studentGradeExcel : workingSchedule) {
                Row row = sheet.createRow(rowIndex);

                Cell cell = row.createCell(0);
                cell.setCellValue(studentGradeExcel.getGradeName());
                sheet.setColumnWidth(0, 30 * 256);
                cell.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(studentGradeExcel.getOpenClassSchoolName());
                sheet.setColumnWidth(1, 20 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(studentGradeExcel.getClassTypeName());
                sheet.setColumnWidth(2, 20 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(3);
                cell3.setCellValue(studentGradeExcel.getStudentName());
                sheet.setColumnWidth(3, 15 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(studentGradeExcel.getLinkman());
                sheet.setColumnWidth(4, 15 * 256);
                cell4.setCellStyle(cellStyle);

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(studentGradeExcel.getLinkmanPhone());
                sheet.setColumnWidth(5, 25 * 256);
                cell5.setCellStyle(cellStyle);

                Cell cell6 = row.createCell(6);
                cell6.setCellValue(studentGradeExcel.getAllCourseCount());
                sheet.setColumnWidth(6, 15 * 256);
                cell6.setCellStyle(cellStyle);

                Cell cell7 = row.createCell(7);
                cell7.setCellValue(studentGradeExcel.getResidueCourseCount());
                sheet.setColumnWidth(7, 15 * 256);
                cell7.setCellStyle(cellStyle);

                Cell cell8 = row.createCell(8);
                cell8.setCellValue(studentGradeExcel.getUseCourseCount());
                sheet.setColumnWidth(8, 20 * 256);
                cell8.setCellStyle(cellStyle);

                Cell cell9 = row.createCell(9);
                cell9.setCellValue(studentGradeExcel.getArriveCount());
                sheet.setColumnWidth(9, 20 * 256);
                cell9.setCellStyle(cellStyle);

                Cell cell10 = row.createCell(10);
                cell10.setCellValue(studentGradeExcel.getRepairCount());
                sheet.setColumnWidth(10, 20 * 256);
                cell10.setCellStyle(cellStyle);

                Cell cell11 = row.createCell(11);
                cell11.setCellValue(studentGradeExcel.getSubjectsName());
                sheet.setColumnWidth(11, 20 * 256);
                cell11.setCellStyle(cellStyle);

                Cell cell12 = row.createCell(12);
                cell12.setCellValue(studentGradeExcel.getSchoolName());
                sheet.setColumnWidth(12, 20 * 256);
                cell12.setCellStyle(cellStyle);

                Cell cell13 = row.createCell(13);
                cell13.setCellValue(studentGradeExcel.getClanStudentName());
                sheet.setColumnWidth(13, 20 * 256);
                cell13.setCellStyle(cellStyle);

                Cell cell14 = row.createCell(14);
                cell14.setCellValue(studentGradeExcel.getClanSubjectName());
                sheet.setColumnWidth(14, 20 * 256);
                cell14.setCellStyle(cellStyle);

                Cell cell15 = row.createCell(15);
                cell15.setCellValue(studentGradeExcel.getClanSchoolName());
                sheet.setColumnWidth(15, 20 * 256);
                cell15.setCellStyle(cellStyle);

                // 班级名称~班型合并逻辑
                if (lastGradeExcel != null && !studentGradeExcel.getGradeName().equals(lastGradeExcel)) {
                    if (rowIndex - lastGradeNameRowIndex > 1) {
                        for (int j = 0; j <= 2; j++) {
                            sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, j, j));
                        }
                    }
                    lastGradeNameRowIndex = rowIndex; // 更新为当前数据行索引
                }
                lastGradeExcel = studentGradeExcel.getGradeName();

                // 学生姓名~请假数量合并逻辑
                if (lastStudentName != null && !studentGradeExcel.getStudentName().equals(lastStudentName)) {
                    if (rowIndex - lastStudentNameRowIndex > 1) {
                        for (int j = 3; j <= 10; j++) {
                            sheet.addMergedRegion(new CellRangeAddress(lastStudentNameRowIndex, rowIndex - 1, j, j));
                        }
                    }
                    lastStudentNameRowIndex = rowIndex; // 更新为当前数据行索引
                }
                lastStudentName = studentGradeExcel.getStudentName();

                rowIndex++;
            }

            // 处理最后一个班级的合并
            if (rowIndex - lastGradeNameRowIndex > 1) {
                for (int j = 0; j <= 2; j++) {
                    sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, j, j));
                }
            }

            // 处理最后一个学生的合并
            if (rowIndex - lastStudentNameRowIndex > 1) {
                for (int j = 3; j <= 10; j++) {
                    sheet.addMergedRegion(new CellRangeAddress(lastStudentNameRowIndex, rowIndex - 1, j, j));
                }
            }
        }

        String fileName = "排班表" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("招生明细导出")
    @GetMapping("/getParticularsExcel")
    public Result getParticularsExcel(@RequestParam Map<String, String> reMap,
                                      @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                                      @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                      @RequestParam(value = "isTrueData", defaultValue = "", required = false) String isTrueData,
                                      @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum) {
        IPage<Map<String, Object>> iPage = new Page<>(-1, -1);

        QueryWrapper<EnrollInfo> enrollDetailQueryWrapper = new QueryWrapper<>();

        String schoolId = reMap.get("schoolId");
        String subjectsId = reMap.get("subjectsId");
        String addDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String studentName = reMap.get("studentName");
        String teacherName = reMap.get("teacherName");
        String checkType = reMap.get("checkType");

        List<String> groupBy = new ArrayList<>();
        groupBy.add("order_id");
        enrollDetailQueryWrapper.groupBy(groupBy);

        enrollDetailQueryWrapper.eq("deleted", 0);
        enrollDetailQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        enrollDetailQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        enrollDetailQueryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        enrollDetailQueryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        enrollDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        enrollDetailQueryWrapper.eq(StringUtils.isNotBlank(isTrueData), "is_true", isTrueData);

        if (StringUtils.isNotBlank(addDate) && StringUtils.isNotBlank(endDate)) {
            enrollDetailQueryWrapper.between("add_date", addDate, endDate);
        } else if (StringUtils.isNotBlank(addDate)) {
            enrollDetailQueryWrapper.eq("add_date", addDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            enrollDetailQueryWrapper.eq("add_date", endDate);
        }

        enrollDetailQueryWrapper.inSql(StringUtils.isNotBlank(studentName), "student_id", "select id from student where name like '%" + studentName + "%'");
        enrollDetailQueryWrapper.inSql(StringUtils.isNotBlank(teacherName), "teacher_id", "select id from staff where name like '%" + teacherName + "%'");

        if (StringUtils.isNotBlank(checkType)) {
            if (checkType.equals("1")) {
                enrollDetailQueryWrapper.eq("not_check_type", 0);
            } else {
                enrollDetailQueryWrapper.gt("not_check_type", 0);
            }
        }

        if (this.sourseLeve.equals(2)) {
            enrollDetailQueryWrapper.eq("teacher_id", this.adminId);
        }
        enrollDetailQueryWrapper.orderByDesc("id");

        List<EnrollDetail> enrollInfoList = iEnrollInfoService.getParticulars(iPage, enrollDetailQueryWrapper).getRecords();

        ExcelExportHandle.export(response, "招生明细", enrollInfoList, EnrollDetail.class);

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("补课记录导出")
    @GetMapping("/studentScoreExcel")
    public Result studentClassLog(
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "courseId", defaultValue = "") String courseId,
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "status", defaultValue = "") String status,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
            @RequestParam(value = "startDate", defaultValue = "") String startDate,
            @RequestParam(value = "endDate", defaultValue = "") String endDate,
            @RequestParam(value = "studentName", defaultValue = "") String studentName,
            @RequestParam(value = "logType", defaultValue = "") String logType,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "repairType") List<String> repairTypeArr,
            @RequestParam(value = "repairDate", defaultValue = "") String repairDate,
            @RequestParam(value = "backDate", defaultValue = "") String backDate,
            @RequestParam(value = "courseType", defaultValue = "") String courseType,
            @RequestParam(value = "yearPart", defaultValue = "", required = false) String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "", required = false) String quarterNum,
            @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType,
            @RequestParam(value = "lessonNum", defaultValue = "", required = false) String lessonNum,
            @RequestParam(value = "courseTypeId", defaultValue = "", required = false) String courseTypeId,
            @RequestParam(value = "idList", defaultValue = "", required = false) String idList) {

        IPage<RecordCourse> iPage = new Page<>(-1, -1);
        QueryWrapper<StudentClassLogRep> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql(StringUtils.isNotBlank(idList), "id", idList);
        Quarter quarterInfo = iQuarterService.getNowQuarter();
        queryWrapper.eq("deleted", 0);
        if (StringUtils.isNotBlank(schoolId)) {
            queryWrapper.inSql("school_id", schoolId);
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);

        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(courseType), "course_type", courseType);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(lessonNum), "lesson_num", lessonNum);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);


        //type等于1正常上课的学生
        //queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"type",1);
        //logType 0上课记录,1补课管理
        if (StringUtils.isNotBlank(logType) && logType.equals("1")) {
            //补课管理
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                queryWrapper.between("school_date", startDate, endDate);
            } else if (StringUtils.isNotBlank(startDate)) {
                queryWrapper.eq("school_date", startDate);
            } else if (StringUtils.isNotBlank(endDate)) {
                queryWrapper.eq("school_date", endDate);
            }
            queryWrapper.eq("status", 2);
            queryWrapper.ne("deduct_type", 4);//扣课时方式，0未知，1自动，2是手动，3满15次后按消课扣课时,4请假超过两次扣除
            queryWrapper.eq(StringUtils.isNotBlank(courseTypeId), "course_type_id ", courseTypeId);
            queryWrapper.ne("is_deduct_house", 3);

            if (repairTypeArr.size() > 0) {
                Collections.sort(repairTypeArr);
                String sql = "(";
                //0未安排，1，已补课，2已安排，3未补已扣
                // 后台的未安排+已安排=未补未扣，后台补课类型增加：未补已扣（10月24）
                for (String repairType : repairTypeArr) {
                    //未安排
                    if (repairType.equals("0")) {
                        //未安排的is_repair为0或者is_repair为2并且结束时间小于等于当前时间
                        sql += "(is_repair=" + repairType + " AND buckle_class_money = 0 or (is_repair=2 AND buckle_class_money = 0 and repair_end_date_time<='" + LocalDateTime.now().withNano(0) + "'))";
                        //queryWrapper.and(i->i.eq("is_repair",repairType).or(j->j.eq("is_repair",2).le("repair_end_date_time",LocalDateTime.now().withNano(0))));
                    } else if (repairType.equals("1")) {
                        if (repairTypeArr.contains("0")) {
                            sql += "or";
                        }
                        sql += "(is_repair = 1)";
                        //queryWrapper.eq("is_repair",repairType);
                    } else if (repairType.equals("2")) {
                        if (repairTypeArr.contains("0") || repairTypeArr.contains("1")) {
                            sql += "or";
                        }
                        sql += " (is_repair=2 AND buckle_class_money = 0 and repair_end_date_time>='" + LocalDateTime.now().withNano(0) + "')";
                        //queryWrapper.eq("is_repair",repairType);
                        //queryWrapper.ge("repair_end_date_time",LocalDateTime.now().withNano(0));
                    } else if (repairType.equals("3")) {// 未补已扣
                        if (repairTypeArr.contains("0") || repairTypeArr.contains("1") || repairTypeArr.contains("2")) {
                            sql += "or";
                        }
                        sql += "(is_repair <> 1 AND is_deduct_house = 1 AND is_deduct_money = 1 AND buckle_class_house > 0 )";
                    }
                }
                sql += ")";
                queryWrapper.apply(sql);
            }
            if (StringUtils.isNotBlank(repairDate)) {
                LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MIN);
                LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MAX);
                queryWrapper.between("repair_end_date_time", startDateTime, endDateTime);
            }
            if (StringUtils.isNotBlank(backDate)) {
                LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(backDate), LocalTime.MIN);
                LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(backDate), LocalTime.MAX);
                queryWrapper.between("back_date", startDateTime, endDateTime);
            }
            //queryWrapper.orderByDesc("school_date");
        } else {
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                queryWrapper.between("school_date", startDate, endDate);
            }
            /*if (StringUtils.isNotBlank(repairDate)) {
                LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MIN);
                LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MAX);
                queryWrapper.between("repair_end_date_time",startDateTime,endDateTime);
            }*/
            if (status.equals("1")) {
                queryWrapper.eq("status", 1);
            } else if (status.equals("2")) {
                queryWrapper.eq("status", 2);
                queryWrapper.ne("is_repair", 1);
            } else if (status.equals("3")) {
                queryWrapper.eq("status", 3);
                queryWrapper.ne("is_repair", 1);
            } else if (status.equals("100")) {//请假已补
                queryWrapper.eq(StringUtils.isNotBlank(status), "status", 2);
                queryWrapper.eq("is_repair", 1);
            } else if (status.equals("101")) {//请假已扣
                queryWrapper.eq(StringUtils.isNotBlank(status), "status", 2);
                queryWrapper.eq("is_deduct_house", 1);
                queryWrapper.eq("is_deduct_money", 1);
                queryWrapper.gt("buckle_class_house", 0);
            }

            //queryWrapper.orderByAsc("school_date");
        }

        if (StringUtils.isNotBlank(studentName)) {
            //queryWrapper.inSql("student_id","select id from student where name like '%"+studentName+"%'");
            queryWrapper.eq("student_name", studentName);
        }

        if (this.sourseLeve.equals(2)) {
            queryWrapper.and(i -> i.eq("old_teacher_id", this.adminId).or().eq("teacher_id", this.adminId));
        }

        List<String> orderBy = new ArrayList<>();
        orderBy.add("school_date");
        orderBy.add("id");
        queryWrapper.orderByDesc(orderBy);

        iRecordCourseService.studentClassLog(iPage, queryWrapper);

        IPage<StudentClassLogRep> studentClassLogRepList = iRecordCourseService.studentClassLog(iPage, queryWrapper);

        if (StringUtils.isNotBlank(logType) && logType.equals("1")) {
            // 在循环外创建缓存
            Map<Long, String> classTypeCache = new HashMap<>();
            Map<Integer, String> yearClassCache = new HashMap<>();

            for (StudentClassLogRep studentClassLogRep : studentClassLogRepList.getRecords()) {
                if (studentClassLogRep.getIsRepair() == 0) {
                    studentClassLogRep.setIsRepairName("未安排");
                } else if (studentClassLogRep.getIsRepair() == 1) {
                    studentClassLogRep.setIsRepairName("已补课");
                } else if (studentClassLogRep.getIsRepair() == 2) {
                    studentClassLogRep.setIsRepairName("已安排");
                }
                studentClassLogRep.setStatusName(studentClassLogRep.getStatus().getValue());

                if (studentClassLogRep.getCourseTypeId() != null) {
                    // 检查缓存中是否存在classTypeCache，如果不存在则进行查询并存入缓存
                    if (!classTypeCache.containsKey(studentClassLogRep.getCourseTypeId())) {
                        classTypeCache.put(studentClassLogRep.getCourseTypeId(), iCourseTypeService.getById(studentClassLogRep.getCourseTypeId()).getName());
                    }
                    studentClassLogRep.setCourseTypeStr(classTypeCache.get(studentClassLogRep.getCourseTypeId()));
                }

                if (studentClassLogRep.getYearClassId() != null) {
                    // 检查缓存中是否存在yearClassCache，如果不存在则进行查询并存入缓存
                    if (!yearClassCache.containsKey(studentClassLogRep.getYearClassId())) {
                        yearClassCache.put(studentClassLogRep.getYearClassId(), CommonUtil.getYearClassNameForId(studentClassLogRep.getYearClassId()));
                    }
                    studentClassLogRep.setYearClassStr(yearClassCache.get(studentClassLogRep.getYearClassId()));
                }
                studentClassLogRep.setSchoolTime(studentClassLogRep.getTimeStart() + " ~ " + studentClassLogRep.getTimeEnd());
            }
            ExcelExportHandle.export(response, "补课记录", studentClassLogRepList.getRecords(), StudentClassLogRep.class);
        } else {
            List<StudentScoreExcel> studentScoreList = new ArrayList<>();
            for (StudentClassLogRep studentClassLogRep : studentClassLogRepList.getRecords()) {
                StudentScoreExcel studentScoreExcel = new StudentScoreExcel();
                studentScoreExcel.setTime(studentClassLogRep.getTimeStart() + " ~ " + studentClassLogRep.getTimeEnd());
                studentScoreExcel.setSchoolDate(studentClassLogRep.getSchoolDate());
                studentScoreExcel.setStudentName(studentClassLogRep.getStudentName());
                studentScoreExcel.setGradeName(studentClassLogRep.getGradeName());
                studentScoreExcel.setSubjectsName(studentClassLogRep.getSubjectsName());
                if (studentClassLogRep.getCourseType().equals(1)) {
                    studentScoreExcel.setReachTypeName("正常");
                } else if (studentClassLogRep.getCourseType().equals(2)) {
                    studentScoreExcel.setReachTypeName("");
                } else if (studentClassLogRep.getCourseType().equals(3)) {
                    studentScoreExcel.setReachTypeName("补课");
                } else if (studentClassLogRep.getCourseType().equals(4)) {
                    studentScoreExcel.setReachTypeName("调课");
                } else if (studentClassLogRep.getCourseType().equals(5)) {
                    studentScoreExcel.setReachTypeName("消课");
                } else if (studentClassLogRep.getCourseType().equals(6)) {
                    studentScoreExcel.setReachTypeName("缺课");
                }
                studentScoreExcel.setStatusName(studentClassLogRep.getStatus().getValue());
                if (studentClassLogRep.getIsRepair().equals(1)) {
                    studentScoreExcel.setStatusName(studentScoreExcel.getStudentName() + "(已补课)");
                }
                studentScoreExcel.setBuckleClassHouse(studentClassLogRep.getBuckleClassHouse() / 3);
                studentScoreExcel.setBuckleClassMoney(studentClassLogRep.getBuckleClassMoney());
                studentScoreExcel.setTeacherName(studentClassLogRep.getTeacherName());
                studentScoreExcel.setSchoolName(studentClassLogRep.getSchoolName());
                studentScoreList.add(studentScoreExcel);
            }
            ExcelExportHandle.export(response, "上课记录", studentScoreList, StudentScoreExcel.class);
        }

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("花名册导出")
    @GetMapping("/rosterExcel")
    public Result rosterExcel(@RequestParam Map<String, String> reMap,
                              @RequestParam(value = "isScheduling", defaultValue = "") String isScheduling,
                              @RequestParam("schoolList") String[] schoolList) throws IOException {
        IPage<Student> iPage = new Page<>(-1, -1);
        String keywordType = reMap.get("keywordSearchType");
        String keyword = reMap.get("name");
        String state = reMap.get("state");
        String isGuanzhu = reMap.get("isGuanzhu");
        String isGather = reMap.get("isGather");
        String isOwn = reMap.get("isOwn");
        String studentId = reMap.get("studentIdList");
        String isCourseHouse = reMap.get("isCourseHouse");
        String isIdCard = reMap.get("isIdCard");

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Long schoolId = 0L;
        String schoolIdStr = "";
        if (schoolList.length > 0) {
            schoolIdStr = String.join(",", schoolList);
            schoolId = Long.parseLong(schoolList[0]);
        } else {
            schoolIdStr = baseSchoolIdStr;
        }

        List<Student> studentList = iStudentService.rosterListExcel(iPage, quarterNow.getYearPart(), quarterNow.getNum(), schoolId, schoolIdStr, state, isGuanzhu, isGather, isOwn, isIdCard, isCourseHouse, isScheduling, keywordType, keyword, this.sourseLeve, this.adminId, studentId).getRecords();

        List<StudentRosterExcel> studentRosterExcels = new ArrayList<>();
        for (Student student : studentList) {
            StudentRosterExcel studentRosterExcel = new StudentRosterExcel();
            studentRosterExcel.setName(student.getName());
            if (student.getSex() == 1) {
                studentRosterExcel.setSex("男");
            } else if (student.getSex() == 2) {
                studentRosterExcel.setSex("女");
            } else {
                studentRosterExcel.setSex("未知");
            }
            StudentAccount studentAccount = iStudentAccountService.getOneForStudentId(student.getId());
            if (studentAccount != null) {
                studentRosterExcel.setAccount(studentAccount.getAccount());
                studentRosterExcel.setPwd(studentAccount.getPwd());
            }

            // 校区
            StringBuffer organizationSb = new StringBuffer();
            for (Organization organization : student.getSignUpSchoolList()) {
                organizationSb.append(organization.getName());
                // 换行
                organizationSb.append("\r\n");
            }
            studentRosterExcel.setSchool(String.valueOf(organizationSb));

            // 联系人
            StringBuffer typeValueDatASb = new StringBuffer();
            for (TypeValueData typeValueData : student.getLinkManList()) {
                if (typeValueData.getTypeId() == 1) {
                    typeValueDatASb.append("父亲 ");
                } else if (typeValueData.getTypeId() == 2) {
                    typeValueDatASb.append("母亲 ");
                } else if (typeValueData.getTypeId() == 3) {
                    typeValueDatASb.append("自己 ");
                } else {
                    typeValueDatASb.append("其他 ");
                }

                typeValueDatASb.append(typeValueData.getContent());
                // 换行
                typeValueDatASb.append("\r\n");
            }
            studentRosterExcel.setLinkman(String.valueOf(typeValueDatASb).trim());

            studentRosterExcels.add(studentRosterExcel);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建顶部样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();
        headList.add("学员姓名");
        headList.add("账号");
        headList.add("密码");
        headList.add("性别");
        headList.add("联系人");
        headList.add("报读校区");

        // 写入表头
        int columnCount = headList.size();

        for (int i = 0; i < columnCount; i++) {
            Row headerRow = sheet.createRow(0);
            for (int j = 0; j < headList.size(); j++) {
                Cell headerCell = headerRow.createCell(j);
                headerCell.setCellValue(headList.get(j));
                headerCell.setCellStyle(cellStyle); // 设置单元格样式
            }
        }

        // 创建顶部样式
        CellStyle cellStyle1 = workbook.createCellStyle();
        Font font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 11);
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 写入数据行
        int rowNum = 1;
        for (StudentRosterExcel scoreDataDetail : studentRosterExcels) {
            Row row = sheet.createRow(rowNum++);
            Cell cell3 = row.createCell(0);
            cell3.setCellValue(scoreDataDetail.getName());
            sheet.setColumnWidth(0, 20 * 256);
            cell3.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell4 = row.createCell(1);
            cell4.setCellValue(scoreDataDetail.getAccount());
            sheet.setColumnWidth(1, 20 * 256);
            cell4.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell5 = row.createCell(2);
            cell5.setCellValue(scoreDataDetail.getPwd());
            sheet.setColumnWidth(1, 20 * 256);
            cell5.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell6 = row.createCell(3);
            cell6.setCellValue(scoreDataDetail.getSex());
            sheet.setColumnWidth(2, 20 * 256);
            cell6.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell7 = row.createCell(4);
            cell7.setCellValue(scoreDataDetail.getLinkman());
            sheet.setColumnWidth(3, 20 * 256);
            cell7.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell8 = row.createCell(5);
            cell8.setCellValue(scoreDataDetail.getSchool().trim());
            cellStyle1.setWrapText(true);//设置为自动换行
            sheet.setColumnWidth(4, 20 * 256);
            cell8.setCellStyle(cellStyle1); // 设置单元格样式
        }

        String fileName = "花名册" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("日程表导出")
    @GetMapping("/calendarExcel")
    public Result calendarExcel(@RequestParam Map<String, String> reMap,
                                @RequestParam(name = "status", required = false) String status,
                                @RequestParam(name = "lessonType", required = false) String lessonType) {
        IPage<CourseSchedulingDetail> iPage = new Page<>(-1, -1);

        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String gradeId = reMap.get("gradeId");
        String teacherId = reMap.get("teacherId");
        String keyType = reMap.get("keyType");
        String keyWord = reMap.get("keyWord");
        String quarterNum = reMap.get("quarterNum");
        String idList = reMap.get("idList");

        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.between("school_date", startDate, endDate);
        } else if (StringUtils.isNotBlank(startDate)) {
            courseSchedulingDetailQueryWrapper.ge("school_date", startDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.le("school_date", endDate);
        }
        if (StringUtils.isNotBlank(keyType) && StringUtils.isNotBlank(keyWord)) {
            //搜索关键词类型：1班级名称，2教师名称，3助教名称，4教室名称
            if (keyType.equals("1")) {
                courseSchedulingDetailQueryWrapper.like("grade_name", keyWord);
            } else if (keyType.equals("2")) {
                courseSchedulingDetailQueryWrapper.like("teacher_name", keyWord);
            } else if (keyType.equals("3")) {
                courseSchedulingDetailQueryWrapper.like("assistant_name", keyWord);
            } else if (keyType.equals("4")) {
                courseSchedulingDetailQueryWrapper.like("class_romm_name", keyWord);
            }
        }

        String schoolId = reMap.get("schoolId");
        if (StringUtils.isNotBlank(schoolId)) {
            courseSchedulingDetailQueryWrapper.eq("school_id", schoolId);
        } else {
            courseSchedulingDetailQueryWrapper.in("school_id", this.baseSchoolIdList);
        }
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(idList), "id", idList);

        courseSchedulingDetailQueryWrapper.eq("deleted", 0);
        courseSchedulingDetailQueryWrapper.orderByAsc("start_date_time");
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.calendarList(iPage, courseSchedulingDetailQueryWrapper).getRecords();

        for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
            courseSchedulingDetail.setTime(courseSchedulingDetail.getTimeStart() + "-" + courseSchedulingDetail.getTimeEnd());
            courseSchedulingDetail.setStatusStr(courseSchedulingDetail.getStatus().getValue());
        }

        try {
            // 使用easyExcel导出表格
            ExcelExportHandle.export(response, "日程表", courseSchedulingDetailList, CourseSchedulingDetail.class);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new Result(Code.ERROR, null, "导出失败");
        }
        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("成绩详情导出")
    @GetMapping("/otherScoreDataDetailExcel")
    public Result otherScoreDataDetailExcel(
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics,
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
            @RequestParam(value = "gradeSection", defaultValue = "") String gradeSection,
            @RequestParam(value = "scoreDetailType", defaultValue = "") String scoreDetailType,
            @RequestParam(value = "include", defaultValue = "1") String include,
            @RequestParam(value = "studentName", defaultValue = "") String studentName,
            @RequestParam(value = "courseTypeId", defaultValue = "") String courseTypeId,
            @RequestParam(value = "status", defaultValue = "") String status,
            @RequestParam(value = "carryStatus", defaultValue = "") String carryStatus,
            @RequestParam(value = "dataType", defaultValue = "1") String dataType
    ) throws IOException {

        if (StringUtils.isEmpty(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        } else if (StringUtils.isEmpty(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        } else if (StringUtils.isEmpty("examNum")) {
            return new Result(Code.ERROR, "", "考试名称不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Code.ERROR, "", "排行不能为空");
        }

        IPage<ScoreDataDetail> iPage = new Page<>(-1, -1);

        List<ScoreDataDetail> excelList = iTranscriptService.otherScoreDataDetail(iPage, schoolId, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, teacherId, gradeId, scoreDetailType, status, include, studentName, courseTypeId, dataType, carryStatus).getRecords();

        /**
         * 不及格、及格
         */
        if (scoreDetailType.equals("1")) {
            //不及格、及格
            List<ScoreDataDetailPassExcel> scoreDataDetailPassExcelList = new ArrayList<>();
            for (ScoreDataDetail detail : excelList) {
                ScoreDataDetailPassExcel scoreDataDetailPassExcel = new ScoreDataDetailPassExcel();
                scoreDataDetailPassExcel.setScore(detail.getScore());
                scoreDataDetailPassExcel.setTeacherName(detail.getTeacherName());
                scoreDataDetailPassExcel.setStudentName(detail.getStudentName());
                scoreDataDetailPassExcel.setYearClassName(detail.getYearClassName());
                scoreDataDetailPassExcelList.add(scoreDataDetailPassExcel);
            }
            ExcelExportHandle.export(response, "成绩详情", scoreDataDetailPassExcelList, ScoreDataDetailPassExcel.class);
        }

        /**
         * 优秀、不优秀
         */
        if (scoreDetailType.equals("2")) {
            Quarter upQuarter = CommonUtil.getUpQuarterForTerm(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
            String examName = CommonUtil.getExamNameForId(Integer.parseInt(examNum));
            String upExamName = CommonUtil.getExamNameForId(upQuarter.getSort());

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");

            // 创建顶部样式
            CellStyle cellStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 12);
            cellStyle.setFont(font);
            cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

            List<String> headList = new ArrayList<>();
            headList.add("学员姓名");
            headList.add(yearPart + CommonUtil.getQuarterNameForId(Integer.parseInt(quarterNum)) + examName);
            headList.add(upQuarter.getYearPart() + upQuarter.getAliasName() + upExamName);
            headList.add("优秀状态");
            headList.add("提分");
            headList.add("带班老师");
            headList.add("年级");

            // 写入表头
            int columnCount = headList.size();

            for (int i = 0; i < columnCount; i++) {
                Row headerRow = sheet.createRow(0);
                for (int j = 0; j < headList.size(); j++) {
                    Cell headerCell = headerRow.createCell(j);
                    headerCell.setCellValue(headList.get(j));
                    headerCell.setCellStyle(cellStyle); // 设置单元格样式
                }
            }

            // 创建顶部样式
            CellStyle cellStyle1 = workbook.createCellStyle();
            Font font1 = workbook.createFont();
            font1.setFontHeightInPoints((short) 11);
            cellStyle1.setFont(font1);
            cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

            // 写入数据行
            int rowNum = 1;
            for (ScoreDataDetail scoreDataDetail : excelList) {
                Row row = sheet.createRow(rowNum++);
                Cell cell0 = row.createCell(0);
                cell0.setCellValue(scoreDataDetail.getStudentName());
                sheet.setColumnWidth(0, 20 * 256);
                cell0.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(scoreDataDetail.getScore());
                sheet.setColumnWidth(1, 20 * 256);
                cell1.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(scoreDataDetail.getScoreB());
                sheet.setColumnWidth(2, 20 * 256);
                cell2.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell3 = row.createCell(3);
                if (scoreDataDetail.getDiffPassCount() != null) {
                    if (scoreDataDetail.getDiffPassCount() == 1) {
                        cell3.setCellValue("优秀提分");
                    } else {
                        cell3.setCellValue("优秀退步");
                    }
                }
                sheet.setColumnWidth(3, 20 * 256);
                cell3.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(scoreDataDetail.getDiffScore().toString());
                sheet.setColumnWidth(4, 20 * 256);
                cell4.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(scoreDataDetail.getTeacherName());
                sheet.setColumnWidth(5, 20 * 256);
                cell5.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell6 = row.createCell(6);
                cell6.setCellValue(scoreDataDetail.getYearClassName());
                sheet.setColumnWidth(6, 20 * 256);
                cell6.setCellStyle(cellStyle1); // 设置单元格样式
            }

            String fileName = "成绩详情" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/zip");//设置为zip格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }

        /**
         * 提分、退步
         */
        if (scoreDetailType.equals("3")) {
            Quarter upQuarter = CommonUtil.getUpQuarterForTerm(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
            String examName = CommonUtil.getExamNameForId(Integer.parseInt(examNum));
            String upExamName = CommonUtil.getExamNameForId(upQuarter.getSort());

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");

            // 创建顶部样式
            CellStyle cellStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 12);
            cellStyle.setFont(font);
            cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

            List<String> headList = new ArrayList<>();
            headList.add("学员姓名");
            headList.add("电话号码");
            headList.add(yearPart + CommonUtil.getQuarterNameForId(Integer.parseInt(quarterNum)) + examName);
            headList.add(upQuarter.getYearPart() + upQuarter.getAliasName() + upExamName);
            headList.add("提分");
            headList.add("带班老师");
            headList.add("年级");

            // 写入表头
            int columnCount = headList.size();

            for (int i = 0; i < columnCount; i++) {
                Row headerRow = sheet.createRow(0);
                for (int j = 0; j < headList.size(); j++) {
                    Cell headerCell = headerRow.createCell(j);
                    headerCell.setCellValue(headList.get(j));
                    headerCell.setCellStyle(cellStyle); // 设置单元格样式
                }
            }

            // 创建顶部样式
            CellStyle cellStyle1 = workbook.createCellStyle();
            Font font1 = workbook.createFont();
            font1.setFontHeightInPoints((short) 11);
            cellStyle1.setFont(font1);
            cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

            // 写入数据行
            int rowNum = 1;
            for (ScoreDataDetail scoreDataDetail : excelList) {
                Row row = sheet.createRow(rowNum++);
                Cell cell1 = row.createCell(0);
                cell1.setCellValue(scoreDataDetail.getStudentName());
                sheet.setColumnWidth(0, 20 * 256);
                cell1.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(scoreDataDetail.getLinkmanPhone());
                sheet.setColumnWidth(1, 20 * 256);
                cell2.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(scoreDataDetail.getScore());
                sheet.setColumnWidth(2, 20 * 256);
                cell3.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell4 = row.createCell(3);
                cell4.setCellValue(scoreDataDetail.getScoreB());
                sheet.setColumnWidth(3, 20 * 256);
                cell4.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell5 = row.createCell(4);
                cell5.setCellValue(scoreDataDetail.getDiffScore().toString());
                sheet.setColumnWidth(4, 20 * 256);
                cell5.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell6 = row.createCell(5);
                cell6.setCellValue(scoreDataDetail.getTeacherName());
                sheet.setColumnWidth(5, 20 * 256);
                cell6.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell7 = row.createCell(6);
                cell7.setCellValue(scoreDataDetail.getYearClassName());
                sheet.setColumnWidth(6, 20 * 256);
                cell7.setCellStyle(cellStyle1); // 设置单元格样式
            }

            String fileName = "成绩详情" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/zip");//设置为zip格式
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新输出流
            outputStream.flush();

            //关闭输出流
            outputStream.close();
        }
        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("实际统计情况导出")
    @GetMapping("/scoreDataDetailExcel")
    public Result scoreDataDetailExcel(
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "examNum", defaultValue = "") String examNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "isStatistics", defaultValue = "") String isStatistics,
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
            @RequestParam(value = "include", defaultValue = "1") String include,
            @RequestParam(value = "studentName", defaultValue = "") String studentName,
            @RequestParam(value = "courseTypeId", defaultValue = "") String courseTypeId,
            @RequestParam(value = "gradeSection", defaultValue = "") String gradeSection,
            @RequestParam(value = "dataType", defaultValue = "1") String dataType
    ) throws IOException {
        if (StringUtils.isEmpty(yearPart)) {
            return new Result(Code.ERROR, "", "年份不能为空");
        } else if (StringUtils.isEmpty(quarterNum)) {
            return new Result(Code.ERROR, "", "学期不能为空");
        } else if (StringUtils.isEmpty(examNum)) {
            return new Result(Code.ERROR, "", "考试名称不能为空");
        } else if (StringUtils.isEmpty(type)) {
            return new Result(Code.ERROR, "", "排行不能为空");
        }

        Quarter upQuarter = CommonUtil.getUpQuarterForTerm(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
        String examName = CommonUtil.getExamNameForId(Integer.parseInt(examNum));
        String upExamName = CommonUtil.getExamNameForId(upQuarter.getSort());

        IPage<ScoreDataDetail> iPage = new Page<>(-1, -1);
        iTranscriptService.scoreDataDetail(iPage, schoolId, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, teacherId, gradeId, isStatistics, include, studentName, courseTypeId, dataType);

        List<ScoreDataDetailExcel> scoreDataDetailExcels = new ArrayList<>();

        for (ScoreDataDetail scoreDataDetail : iPage.getRecords()) {
            ScoreDataDetailExcel scoreDataDetailExcel = new ScoreDataDetailExcel();
            scoreDataDetailExcel.setStudentName(scoreDataDetail.getStudentName());
            if (scoreDataDetail.getIsStatistics().equals("0") || scoreDataDetail.getIsStatistics() == 0) {
                scoreDataDetailExcel.setIsStatisticsA("未统计");
            } else {
                scoreDataDetailExcel.setIsStatisticsA(String.valueOf(scoreDataDetail.getScore()));
            }
            if (scoreDataDetail.getIsStatisticsB().equals("0") || scoreDataDetail.getIsStatisticsB() == 0) {
                scoreDataDetailExcel.setIsStatisticsB("未统计");
            } else {
                scoreDataDetailExcel.setIsStatisticsB(String.valueOf(scoreDataDetail.getScoreB()));
            }
            scoreDataDetailExcel.setSchoolName(scoreDataDetail.getSchoolName());
            scoreDataDetailExcel.setYearClassName(scoreDataDetail.getYearClassName());
            scoreDataDetailExcel.setTeacherName(scoreDataDetail.getTeacherName());
            scoreDataDetailExcel.setReadeSchool(scoreDataDetail.getReadeSchool());  //就读学校
            scoreDataDetailExcels.add(scoreDataDetailExcel);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建顶部样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();
        headList.add("学员姓名");
        headList.add(yearPart + CommonUtil.getQuarterNameForId(Integer.parseInt(quarterNum)) + examName);
        headList.add(upQuarter.getYearPart() + upQuarter.getAliasName() + upExamName);
        headList.add("校区");
        headList.add("就读学校");
        headList.add("年级");
        headList.add("带班老师");

        // 写入表头
        int columnCount = headList.size();

        for (int i = 0; i < columnCount; i++) {
            Row headerRow = sheet.createRow(0);
            for (int j = 0; j < headList.size(); j++) {
                Cell headerCell = headerRow.createCell(j);
                headerCell.setCellValue(headList.get(j));
                headerCell.setCellStyle(cellStyle); // 设置单元格样式
            }
        }

        // 创建顶部样式
        CellStyle cellStyle1 = workbook.createCellStyle();
        Font font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 11);
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 写入数据行
        int rowNum = 1;
        for (ScoreDataDetailExcel scoreDataDetailExcel : scoreDataDetailExcels) {
            Row row = sheet.createRow(rowNum++);
            Cell cell3 = row.createCell(0);
            cell3.setCellValue(scoreDataDetailExcel.getStudentName());
            sheet.setColumnWidth(0, 20 * 256);
            cell3.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell4 = row.createCell(1);
            cell4.setCellValue(scoreDataDetailExcel.getIsStatisticsA());
            sheet.setColumnWidth(1, 20 * 256);
            cell4.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell5 = row.createCell(2);
            cell5.setCellValue(scoreDataDetailExcel.getIsStatisticsB());
            sheet.setColumnWidth(2, 20 * 256);
            cell5.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell6 = row.createCell(3);
            cell6.setCellValue(scoreDataDetailExcel.getSchoolName());
            sheet.setColumnWidth(3, 20 * 256);
            cell6.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell7 = row.createCell(4);
            cell7.setCellValue(scoreDataDetailExcel.getReadeSchool());
            sheet.setColumnWidth(4, 20 * 256);
            cell7.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell8 = row.createCell(5);
            cell8.setCellValue(scoreDataDetailExcel.getYearClassName());
            sheet.setColumnWidth(5, 20 * 256);
            cell8.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell9 = row.createCell(6);
            cell9.setCellValue(scoreDataDetailExcel.getTeacherName());
            sheet.setColumnWidth(6, 20 * 256);
            cell9.setCellStyle(cellStyle1); // 设置单元格样式
        }

        String fileName = "实际统计情况" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("教学服务反馈导出（英语）")
    @GetMapping("/serviceFeedbackEnExcel")
    public Result serviceFeedbackEnExcel(
            @RequestParam(value = "yearPart", required = true) Integer yearPart,
            @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
            @RequestParam(value = "subjectsId", required = false) Long subjectsId,
            @RequestParam(value = "gradeId", required = false) Long gradeId,
            @RequestParam(value = "teacherId", required = false) Long teacherId,
            @RequestParam(value = "idList", required = false) String idList,
            @RequestParam(value = "lessonNum", required = false) Integer lessonNum,
            @RequestParam(value = "studentName", defaultValue = "") String studentName) throws IOException {
        IPage<ServiceFeedback> iPage = new Page<>(-1, -1);
        iServiceFeedbackService.getFeedBadckList(iPage, yearPart, quarterNum, schoolId, yearClassId, teacherId, gradeId, subjectsId, lessonNum, studentName, idList);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 第一行
        Row headerRow1 = sheet.createRow(0);
        // 第二行
        Row headerRow2 = sheet.createRow(1);

        /**
         * 第一块
         */
        CellRangeAddress address1 = new CellRangeAddress(0, 2, 0, 0);
        sheet.addMergedRegion(address1);
        Cell headerCell1 = headerRow1.createCell(0);
        headerCell1.setCellValue("学员名字");
        headerCell1.setCellStyle(cellStyle);
        sheet.createFreezePane(1, 0); // 冻结首列

        CellRangeAddress address2 = new CellRangeAddress(0, 2, 1, 1);
        sheet.addMergedRegion(address2);
        Cell headerCell2 = headerRow1.createCell(1);
        headerCell2.setCellValue("教师");
        headerCell2.setCellStyle(cellStyle);

        CellRangeAddress address3 = new CellRangeAddress(0, 2, 2, 2);
        sheet.addMergedRegion(address3);
        Cell headerCell3 = headerRow1.createCell(2);
        headerCell3.setCellValue("课次");
        headerCell3.setCellStyle(cellStyle);

        CellRangeAddress address4 = new CellRangeAddress(0, 2, 3, 3);
        sheet.addMergedRegion(address4);
        Cell headerCell4 = headerRow1.createCell(3);
        headerCell4.setCellValue("班级");
        headerCell4.setCellStyle(cellStyle);

        CellRangeAddress address5 = new CellRangeAddress(0, 2, 4, 4);
        sheet.addMergedRegion(address5);
        Cell headerCell5 = headerRow1.createCell(4);
        headerCell5.setCellValue("校区");
        headerCell5.setCellStyle(cellStyle);

        /**
         * 第二块
         */
        CellRangeAddress address6 = new CellRangeAddress(0, 0, 5, 8);
        sheet.addMergedRegion(address6);
        Cell headerCell6 = headerRow1.createCell(5);
        headerCell6.setCellValue("精品课");
        headerCell6.setCellStyle(cellStyle);

        CellRangeAddress address7 = new CellRangeAddress(0, 0, 9, 11);
        sheet.addMergedRegion(address7);
        Cell headerCell7 = headerRow1.createCell(9);
        headerCell7.setCellValue("智能课");
        headerCell7.setCellStyle(cellStyle);

        CellRangeAddress address8 = new CellRangeAddress(0, 0, 12, 17);
        sheet.addMergedRegion(address8);
        Cell headerCell8 = headerRow1.createCell(12);
        headerCell8.setCellValue("线上打卡");
        headerCell8.setCellStyle(cellStyle);

        CellRangeAddress address9 = new CellRangeAddress(0, 0, 18, 23);
        sheet.addMergedRegion(address9);
        Cell headerCell9 = headerRow1.createCell(18);
        headerCell9.setCellValue("检测情况");
        headerCell9.setCellStyle(cellStyle);

        CellRangeAddress address10 = new CellRangeAddress(0, 0, 24, 25);
        sheet.addMergedRegion(address10);
        Cell headerCell10 = headerRow1.createCell(24);
        headerCell10.setCellValue("留言区");
        headerCell10.setCellStyle(cellStyle);

        /**
         * 第三块
         */
        CellRangeAddress address11 = new CellRangeAddress(1, 2, 5, 5);
        sheet.addMergedRegion(address11);
        Cell headerCell11 = headerRow2.createCell(5);
        headerCell11.setCellValue("出勤情况");
        headerCell11.setCellStyle(cellStyle);

        CellRangeAddress address12 = new CellRangeAddress(1, 2, 6, 6);
        sheet.addMergedRegion(address12);
        Cell headerCell12 = headerRow2.createCell(6);
        headerCell12.setCellValue("认真听讲");
        headerCell12.setCellStyle(cellStyle);

        CellRangeAddress address13 = new CellRangeAddress(1, 2, 7, 7);
        sheet.addMergedRegion(address13);
        Cell headerCell13 = headerRow2.createCell(7);
        headerCell13.setCellValue("积极互动");
        headerCell13.setCellStyle(cellStyle);

        CellRangeAddress address14 = new CellRangeAddress(1, 2, 8, 8);
        sheet.addMergedRegion(address14);
        Cell headerCell14 = headerRow2.createCell(8);
        headerCell14.setCellValue("掌握情况");
        headerCell14.setCellStyle(cellStyle);

        CellRangeAddress address15 = new CellRangeAddress(1, 2, 9, 9);
        sheet.addMergedRegion(address15);
        Cell headerCell15 = headerRow2.createCell(9);
        headerCell15.setCellValue("应通关");
        headerCell15.setCellStyle(cellStyle);

        CellRangeAddress address16 = new CellRangeAddress(1, 2, 10, 10);
        sheet.addMergedRegion(address16);
        Cell headerCell16 = headerRow2.createCell(10);
        headerCell16.setCellValue("已通过");
        headerCell16.setCellStyle(cellStyle);

        CellRangeAddress address17 = new CellRangeAddress(1, 2, 11, 11);
        sheet.addMergedRegion(address17);
        Cell headerCell17 = headerRow2.createCell(11);
        headerCell17.setCellValue("通关率");
        headerCell17.setCellStyle(cellStyle);

        CellRangeAddress address18 = new CellRangeAddress(1, 2, 12, 12);
        sheet.addMergedRegion(address18);
        Cell headerCell18 = headerRow2.createCell(12);
        headerCell18.setCellValue("周一");
        sheet.setColumnWidth(12, 15 * 256);
        headerCell18.setCellStyle(cellStyle);

        CellRangeAddress address19 = new CellRangeAddress(1, 2, 13, 13);
        sheet.addMergedRegion(address19);
        Cell headerCell19 = headerRow2.createCell(13);
        headerCell19.setCellValue("周二");
        sheet.setColumnWidth(13, 15 * 256);
        headerCell19.setCellStyle(cellStyle);

        CellRangeAddress address20 = new CellRangeAddress(1, 2, 14, 14);
        sheet.addMergedRegion(address20);
        Cell headerCell20 = headerRow2.createCell(14);
        headerCell20.setCellValue("周三");
        sheet.setColumnWidth(14, 15 * 256);
        headerCell20.setCellStyle(cellStyle);

        CellRangeAddress address21 = new CellRangeAddress(1, 2, 15, 15);
        sheet.addMergedRegion(address21);
        Cell headerCell21 = headerRow2.createCell(15);
        headerCell21.setCellValue("周四");
        sheet.setColumnWidth(15, 15 * 256);
        headerCell21.setCellStyle(cellStyle);

        CellRangeAddress address22 = new CellRangeAddress(1, 2, 16, 16);
        sheet.addMergedRegion(address22);
        Cell headerCell22 = headerRow2.createCell(16);
        headerCell22.setCellValue("周五");
        sheet.setColumnWidth(16, 15 * 256);
        headerCell22.setCellStyle(cellStyle);

        CellRangeAddress address23 = new CellRangeAddress(1, 2, 17, 17);
        sheet.addMergedRegion(address23);
        Cell headerCell23 = headerRow2.createCell(17);
        headerCell23.setCellValue("周末");
        sheet.setColumnWidth(17, 15 * 256);
        headerCell23.setCellStyle(cellStyle);

        CellRangeAddress address24 = new CellRangeAddress(1, 2, 24, 24);
        sheet.addMergedRegion(address24);
        Cell headerCell24 = headerRow2.createCell(24);
        headerCell24.setCellValue("精品课老师反馈");
        headerCell24.setCellStyle(cellStyle);

        CellRangeAddress address25 = new CellRangeAddress(1, 2, 25, 25);
        sheet.addMergedRegion(address25);
        Cell headerCell25 = headerRow2.createCell(25);
        headerCell25.setCellValue("刷题班老师反馈");
        headerCell25.setCellStyle(cellStyle);

        /**
         * 第四块
         */
        CellRangeAddress address26 = new CellRangeAddress(1, 1, 18, 19);
        sheet.addMergedRegion(address26);
        Cell headerCell26 = headerRow2.createCell(18);
        headerCell26.setCellValue("词汇（个）");
        headerCell26.setCellStyle(cellStyle);

        CellRangeAddress address27 = new CellRangeAddress(1, 1, 20, 21);
        sheet.addMergedRegion(address27);
        Cell headerCell27 = headerRow2.createCell(20);
        headerCell27.setCellValue("句子（个）");
        headerCell27.setCellStyle(cellStyle);

        CellRangeAddress address28 = new CellRangeAddress(1, 1, 22, 23);
        sheet.addMergedRegion(address28);
        Cell headerCell28 = headerRow2.createCell(22);
        headerCell28.setCellValue("习题（道）");
        headerCell28.setCellStyle(cellStyle);

        /**
         * 第五块
         */
        Row row1 = sheet.createRow(2);
        Cell cell = row1.createCell(18);
        cell.setCellValue("正确");
        sheet.setColumnWidth(0, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(19);
        cell.setCellValue("错误");
        sheet.setColumnWidth(0, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(20);
        cell.setCellValue("正确");
        sheet.setColumnWidth(0, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(21);
        cell.setCellValue("错误");
        sheet.setColumnWidth(0, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(22);
        cell.setCellValue("正确");
        sheet.setColumnWidth(0, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(23);
        cell.setCellValue("错误");
        sheet.setColumnWidth(0, 20 * 256);
        cell.setCellStyle(cellStyle);

        // 写入数据行
        int rowNum = 3;
        for (ServiceFeedback serviceFeedback : iPage.getRecords()) {
            Row row = sheet.createRow(rowNum++);
            Cell cell1 = row.createCell(0);
            cell1.setCellValue(serviceFeedback.getStudentName());
            sheet.setColumnWidth(0, 15 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(serviceFeedback.getTeacherName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue("第" + serviceFeedback.getLessonNum() + "课次");
            sheet.setColumnWidth(2, 15 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(3);
            cell4.setCellValue(serviceFeedback.getGradeName());
            sheet.setColumnWidth(3, 25 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(4);
            cell5.setCellValue(serviceFeedback.getSchoolName());
            sheet.setColumnWidth(4, 25 * 256);
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(5);
            if (serviceFeedback.getSignIn01() != null) {
                if (serviceFeedback.getSignIn01() == 1) {
                    cell6.setCellValue("准时");
                } else if (serviceFeedback.getSignIn01() == 2) {
                    cell6.setCellValue("迟到");
                } else if (serviceFeedback.getSignIn01() == 3) {
                    cell6.setCellValue("请假");
                } else if (serviceFeedback.getSignIn01() == 4) {
                    cell6.setCellValue("缺课");
                } else if (serviceFeedback.getSignIn01() == 5) {
                    cell6.setCellValue("调课");
                } else if (serviceFeedback.getSignIn01() == 6) {
                    cell6.setCellValue("请假（已补课）");
                } else {
                    cell6.setCellValue("缺课（已补课）");
                }
                cell6.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(5, 15 * 256);

            Cell cell7 = row.createCell(6);
            if (serviceFeedback.getTag01() != null) {
                if (serviceFeedback.getTag01() == 1) {
                    cell7.setCellValue("很好");
                } else if (serviceFeedback.getTag01() == 2) {
                    cell7.setCellValue("良好");
                } else {
                    cell7.setCellValue("一般");
                }
                cell7.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(6, 15 * 256);

            Cell cell8 = row.createCell(7);
            if (serviceFeedback.getTag02() != null) {
                if (serviceFeedback.getTag02() == 1) {
                    cell8.setCellValue("很好");
                } else if (serviceFeedback.getTag02() == 2) {
                    cell8.setCellValue("良好");
                } else {
                    cell8.setCellValue("一般");
                }
                cell8.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(7, 15 * 256);

            Cell cell9 = row.createCell(8);
            if (serviceFeedback.getTag03() != null) {
                if (serviceFeedback.getTag03() == 1) {
                    cell9.setCellValue("很好");
                } else if (serviceFeedback.getTag03() == 2) {
                    cell9.setCellValue("良好");
                } else {
                    cell9.setCellValue("一般");
                }
                cell9.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(8, 15 * 256);

            if ((serviceFeedback.getShowPassNum01() != null)) {
                Cell cell10 = row.createCell(9);
                cell10.setCellValue(serviceFeedback.getShowPassNum01());
                sheet.setColumnWidth(9, 15 * 256);
                cell10.setCellStyle(cellStyle);
            }

            if (serviceFeedback.getPassNum01() != null) {
                Cell cell11 = row.createCell(10);
                cell11.setCellValue(serviceFeedback.getPassNum01());
                sheet.setColumnWidth(10, 15 * 256);
                cell11.setCellStyle(cellStyle);
            }

            Cell cell12 = row.createCell(11);
            if (serviceFeedback.getPassNum01() != null) {
                Integer passPercentage = BigDecimal.valueOf(serviceFeedback.getPassNum01()).divide(BigDecimal.valueOf(serviceFeedback.getShowPassNum01()), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).intValue();
                if (passPercentage != null && passPercentage >= 100) {
                    cell12.setCellValue("100%");
                } else {
                    cell12.setCellValue(passPercentage + "%");
                }
            }
            cell12.setCellStyle(cellStyle);
            sheet.setColumnWidth(11, 15 * 256);

            if (serviceFeedback.getPuchCardList() != null || Objects.nonNull(serviceFeedback.getPuchCardList())) {
                for (ServicePuchCard servicePuchCard : serviceFeedback.getPuchCardList()) {
                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 1) {
                        Cell cell13 = row.createCell(12);
                        if (servicePuchCard.getStatus() == 1) {
                            cell13.setCellValue("已打卡");
                        } else {
                            cell13.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(12, 15 * 256);
                        cell13.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 2) {
                        Cell cell14 = row.createCell(13);
                        if (servicePuchCard.getStatus() == 1) {
                            cell14.setCellValue("已打卡");
                        } else {
                            cell14.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(13, 15 * 256);
                        cell14.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 3) {
                        Cell cell15 = row.createCell(14);
                        if (servicePuchCard.getStatus() == 1) {
                            cell15.setCellValue("已打卡");
                        } else {
                            cell15.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(14, 15 * 256);
                        cell15.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 4) {
                        Cell cell16 = row.createCell(15);
                        if (servicePuchCard.getStatus() == 1) {
                            cell16.setCellValue("已打卡");
                        } else {
                            cell16.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(15, 15 * 256);
                        cell16.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 5) {
                        Cell cell17 = row.createCell(16);
                        if (servicePuchCard.getStatus() == 1) {
                            cell17.setCellValue("已打卡");
                        } else {
                            cell17.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(16, 15 * 256);
                        cell17.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 6) {
                        Cell cell18 = row.createCell(17);
                        if (servicePuchCard.getStatus() == 1) {
                            cell18.setCellValue("已打卡");
                        } else {
                            cell18.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(17, 15 * 256);
                        cell18.setCellStyle(cellStyle);
                    }
                }
            }

            for (ServiceDetection serviceDetection : serviceFeedback.getDetectionList()) {
                if (serviceDetection.getType() == 1) {
                    Cell cell19 = row.createCell(18);
                    if (serviceDetection.getRightNum() != null) {
                        cell19.setCellValue(serviceDetection.getRightNum());
                    } else {
                        cell19.setCellValue(0);
                    }
                    sheet.setColumnWidth(18, 15 * 256);
                    cell19.setCellStyle(cellStyle);

                    Cell cell20 = row.createCell(19);
                    if (serviceDetection.getErrorNum() != null) {
                        cell20.setCellValue(serviceDetection.getErrorNum());
                    } else {
                        cell20.setCellValue(0);
                    }
                    sheet.setColumnWidth(19, 15 * 256);
                    cell20.setCellStyle(cellStyle);
                }

                if (serviceDetection.getType() == 2) {
                    Cell cell21 = row.createCell(20);
                    if (serviceDetection.getRightNum() != null) {
                        cell21.setCellValue(serviceDetection.getRightNum());
                    } else {
                        cell21.setCellValue(0);
                    }
                    sheet.setColumnWidth(20, 15 * 256);
                    cell21.setCellStyle(cellStyle);

                    Cell cell22 = row.createCell(21);
                    if (serviceDetection.getErrorNum() != null) {
                        cell22.setCellValue(serviceDetection.getErrorNum());
                    } else {
                        cell22.setCellValue(0);
                    }
                    sheet.setColumnWidth(21, 15 * 256);
                    cell22.setCellStyle(cellStyle);
                }

                if (serviceDetection.getType() == 3) {
                    Cell cell23 = row.createCell(22);
                    if (serviceDetection.getRightNum() != null) {
                        cell23.setCellValue(serviceDetection.getRightNum());
                    } else {
                        cell23.setCellValue(0);
                    }
                    sheet.setColumnWidth(22, 15 * 256);
                    cell23.setCellStyle(cellStyle);

                    Cell cell24 = row.createCell(23);
                    if (serviceDetection.getErrorNum() != null) {
                        cell24.setCellValue(serviceDetection.getErrorNum());
                    } else {
                        cell24.setCellValue(0);
                    }
                    sheet.setColumnWidth(23, 15 * 256);
                    cell24.setCellStyle(cellStyle);
                }
            }

            Cell cell25 = row.createCell(24);
            if (serviceFeedback.getLeaveMsg01() != null) {
                cell25.setCellValue(serviceFeedback.getLeaveMsg01());
            }
            sheet.setColumnWidth(24, 15 * 256);
            cell25.setCellStyle(cellStyle);

            Cell cell26 = row.createCell(25);
            if (serviceFeedback.getLeaveMsg02() != null) {
                cell26.setCellValue(serviceFeedback.getLeaveMsg02());
            }
            sheet.setColumnWidth(25, 15 * 256);
            cell26.setCellStyle(cellStyle);

        }

        String fileName = "英语教学服务反馈" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("教学服务反馈导出（数学和物理）")
    @GetMapping("/serviceFeedbackMaExcel")
    public Result serviceFeedbackMaExcel(
            @RequestParam(value = "yearPart", required = true) Integer yearPart,
            @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
            @RequestParam(value = "schoolId", required = false) Long schoolId,
            @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
            @RequestParam(value = "subjectsId", required = false) Long subjectsId,
            @RequestParam(value = "gradeId", required = false) Long gradeId,
            @RequestParam(value = "teacherId", required = false) Long teacherId,
            @RequestParam(value = "idList", required = false) String idList,
            @RequestParam(value = "lessonNum", required = false) Integer lessonNum,
            @RequestParam(value = "studentName", defaultValue = "") String studentName) throws IOException {
        IPage<ServiceFeedback> iPage = new Page<>(-1, -1);
        iServiceFeedbackService.getFeedBadckList(iPage, yearPart, quarterNum, schoolId, yearClassId, teacherId, gradeId, subjectsId, lessonNum, studentName, idList);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 第一行
        Row headerRow1 = sheet.createRow(0);
        // 第二行
        Row headerRow2 = sheet.createRow(1);

        /**
         * 第一块
         */
        CellRangeAddress address1 = new CellRangeAddress(0, 2, 0, 0);
        sheet.addMergedRegion(address1);
        Cell headerCell1 = headerRow1.createCell(0);
        headerCell1.setCellValue("学员名字");
        headerCell1.setCellStyle(cellStyle);
        sheet.createFreezePane(1, 0); // 冻结首列

        CellRangeAddress address2 = new CellRangeAddress(0, 2, 1, 1);
        sheet.addMergedRegion(address2);
        Cell headerCell2 = headerRow1.createCell(1);
        headerCell2.setCellValue("班级");
        headerCell2.setCellStyle(cellStyle);

        CellRangeAddress address3 = new CellRangeAddress(0, 2, 2, 2);
        sheet.addMergedRegion(address3);
        Cell headerCell3 = headerRow1.createCell(2);
        headerCell3.setCellValue("课次");
        headerCell3.setCellStyle(cellStyle);

        CellRangeAddress address31 = new CellRangeAddress(0, 2, 22, 22);
        sheet.addMergedRegion(address31);
        Cell headerCell31 = headerRow1.createCell(22);
        headerCell31.setCellValue("课堂检测");
        headerCell31.setCellStyle(cellStyle);

        /**
         * 第二块
         */
        CellRangeAddress address6 = new CellRangeAddress(0, 0, 3, 6);
        sheet.addMergedRegion(address6);
        Cell headerCell6 = headerRow1.createCell(3);
        headerCell6.setCellValue("精品课");
        sheet.setColumnWidth(3, 15 * 256);
        headerCell6.setCellStyle(cellStyle);

        CellRangeAddress address7 = new CellRangeAddress(0, 0, 7, 15);
        sheet.addMergedRegion(address7);
        Cell headerCell7 = headerRow1.createCell(7);
        headerCell7.setCellValue("刷题课");
        sheet.setColumnWidth(7, 15 * 256);
        headerCell7.setCellStyle(cellStyle);

        CellRangeAddress address8 = new CellRangeAddress(0, 0, 16, 21);
        sheet.addMergedRegion(address8);
        Cell headerCell8 = headerRow1.createCell(16);
        sheet.setColumnWidth(16, 15 * 256);
        headerCell8.setCellValue("线上打卡");
        headerCell8.setCellStyle(cellStyle);

        CellRangeAddress address10 = new CellRangeAddress(0, 0, 23, 25);
        sheet.addMergedRegion(address10);
        Cell headerCell10 = headerRow1.createCell(23);
        sheet.setColumnWidth(3, 15 * 256);
        headerCell10.setCellValue("留言区");
        headerCell10.setCellStyle(cellStyle);

        /**
         * 第三块
         */
        CellRangeAddress address11 = new CellRangeAddress(1, 2, 3, 3);
        sheet.addMergedRegion(address11);
        Cell headerCell11 = headerRow2.createCell(3);
        headerCell11.setCellValue("出勤情况");
        headerCell11.setCellStyle(cellStyle);

        CellRangeAddress address12 = new CellRangeAddress(1, 2, 4, 4);
        sheet.addMergedRegion(address12);
        Cell headerCell12 = headerRow2.createCell(4);
        headerCell12.setCellValue("认真听讲");
        headerCell12.setCellStyle(cellStyle);

        CellRangeAddress address13 = new CellRangeAddress(1, 2, 5, 5);
        sheet.addMergedRegion(address13);
        Cell headerCell13 = headerRow2.createCell(5);
        headerCell13.setCellValue("积极互动");
        headerCell13.setCellStyle(cellStyle);

        CellRangeAddress address14 = new CellRangeAddress(1, 2, 6, 6);
        sheet.addMergedRegion(address14);
        Cell headerCell14 = headerRow2.createCell(6);
        headerCell14.setCellValue("上课笔记");
        headerCell14.setCellStyle(cellStyle);

        CellRangeAddress address15 = new CellRangeAddress(1, 2, 7, 7);
        sheet.addMergedRegion(address15);
        Cell headerCell15 = headerRow2.createCell(7);
        headerCell15.setCellValue("出勤情况");
        headerCell15.setCellStyle(cellStyle);

        CellRangeAddress address16 = new CellRangeAddress(1, 2, 8, 8);
        sheet.addMergedRegion(address16);
        Cell headerCell16 = headerRow2.createCell(8);
        headerCell16.setCellValue("掌握情况");
        headerCell16.setCellStyle(cellStyle);

        CellRangeAddress address17 = new CellRangeAddress(1, 2, 9, 9);
        sheet.addMergedRegion(address17);
        Cell headerCell17 = headerRow2.createCell(9);
        headerCell17.setCellValue("解题规范");
        headerCell17.setCellStyle(cellStyle);

        CellRangeAddress address18 = new CellRangeAddress(1, 2, 16, 16);
        sheet.addMergedRegion(address18);
        Cell headerCell18 = headerRow2.createCell(16);
        headerCell18.setCellValue("周一");
        sheet.setColumnWidth(16, 15 * 256);
        headerCell18.setCellStyle(cellStyle);

        CellRangeAddress address19 = new CellRangeAddress(1, 2, 17, 17);
        sheet.addMergedRegion(address19);
        Cell headerCell19 = headerRow2.createCell(17);
        headerCell19.setCellValue("周二");
        sheet.setColumnWidth(17, 15 * 256);
        headerCell19.setCellStyle(cellStyle);

        CellRangeAddress address20 = new CellRangeAddress(1, 2, 18, 18);
        sheet.addMergedRegion(address20);
        Cell headerCell20 = headerRow2.createCell(18);
        headerCell20.setCellValue("周三");
        sheet.setColumnWidth(18, 15 * 256);
        headerCell20.setCellStyle(cellStyle);

        CellRangeAddress address21 = new CellRangeAddress(1, 2, 19, 19);
        sheet.addMergedRegion(address21);
        Cell headerCell21 = headerRow2.createCell(19);
        headerCell21.setCellValue("周四");
        sheet.setColumnWidth(19, 15 * 256);
        headerCell21.setCellStyle(cellStyle);

        CellRangeAddress address22 = new CellRangeAddress(1, 2, 20, 20);
        sheet.addMergedRegion(address22);
        Cell headerCell22 = headerRow2.createCell(20);
        headerCell22.setCellValue("周五");
        sheet.setColumnWidth(20, 15 * 256);
        headerCell22.setCellStyle(cellStyle);

        CellRangeAddress address23 = new CellRangeAddress(1, 2, 21, 21);
        sheet.addMergedRegion(address23);
        Cell headerCell23 = headerRow2.createCell(21);
        headerCell23.setCellValue("周末");
        sheet.setColumnWidth(21, 15 * 256);
        headerCell23.setCellStyle(cellStyle);

        CellRangeAddress address24 = new CellRangeAddress(1, 2, 23, 23);
        sheet.addMergedRegion(address24);
        Cell headerCell24 = headerRow2.createCell(23);
        headerCell24.setCellValue("精品课老师反馈");
        sheet.setColumnWidth(23, 20 * 256);
        headerCell24.setCellStyle(cellStyle);

        CellRangeAddress address25 = new CellRangeAddress(1, 2, 24, 24);
        sheet.addMergedRegion(address25);
        Cell headerCell25 = headerRow2.createCell(24);
        headerCell25.setCellValue("刷题班老师反馈");
        sheet.setColumnWidth(24, 20 * 256);
        headerCell25.setCellStyle(cellStyle);

        CellRangeAddress address26 = new CellRangeAddress(1, 2, 25, 25);
        sheet.addMergedRegion(address26);
        Cell headerCell26 = headerRow2.createCell(25);
        headerCell26.setCellValue("经纪老师反馈");
        sheet.setColumnWidth(25, 20 * 256);
        headerCell26.setCellStyle(cellStyle);

        /**
         * 第四块
         */
        CellRangeAddress address27 = new CellRangeAddress(1, 1, 10, 12);
        sheet.addMergedRegion(address27);
        Cell headerCell27 = headerRow2.createCell(10);
        headerCell27.setCellValue("训练区");
        headerCell27.setCellStyle(cellStyle);

        CellRangeAddress address28 = new CellRangeAddress(1, 1, 13, 15);
        sheet.addMergedRegion(address28);
        Cell headerCell28 = headerRow2.createCell(13);
        headerCell28.setCellValue("挑战区");
        headerCell28.setCellStyle(cellStyle);

        /**
         * 第五块
         */
        Row row1 = sheet.createRow(2);
        Cell cell = row1.createCell(10);
        cell.setCellValue("应通关");
        sheet.setColumnWidth(15, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(11);
        cell.setCellValue("已通关");
        sheet.setColumnWidth(15, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(12);
        cell.setCellValue("通关率");
        sheet.setColumnWidth(15, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(13);
        cell.setCellValue("应通关");
        sheet.setColumnWidth(15, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(14);
        cell.setCellValue("已通关");
        sheet.setColumnWidth(15, 20 * 256);
        cell.setCellStyle(cellStyle);

        cell = row1.createCell(15);
        cell.setCellValue("通关率");
        sheet.setColumnWidth(15, 20 * 256);
        cell.setCellStyle(cellStyle);


        // 写入数据行
        int rowNum = 3;
        for (ServiceFeedback serviceFeedback : iPage.getRecords()) {
            Row row = sheet.createRow(rowNum++);
            Cell cell1 = row.createCell(0);
            cell1.setCellValue(serviceFeedback.getStudentName());
            sheet.setColumnWidth(0, 15 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(serviceFeedback.getGradeName());
            sheet.setColumnWidth(1, 30 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue("第" + serviceFeedback.getLessonNum() + "课次");
            sheet.setColumnWidth(2, 15 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(3);
            if (serviceFeedback.getSignIn01() != null) {
                if (serviceFeedback.getSignIn01() == 1) {
                    cell6.setCellValue("准时");
                } else if (serviceFeedback.getSignIn01() == 2) {
                    cell6.setCellValue("迟到");
                } else if (serviceFeedback.getSignIn01() == 3) {
                    cell6.setCellValue("请假");
                } else if (serviceFeedback.getSignIn01() == 4) {
                    cell6.setCellValue("缺课");
                } else if (serviceFeedback.getSignIn01() == 5) {
                    cell6.setCellValue("调课");
                } else if (serviceFeedback.getSignIn01() == 6) {
                    cell6.setCellValue("请假（已补课）");
                } else {
                    cell6.setCellValue("缺课（已补课）");
                }
                cell6.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(3, 15 * 256);

            Cell cell7 = row.createCell(4);
            if (serviceFeedback.getTag01() != null) {
                if (serviceFeedback.getTag01() == 1) {
                    cell7.setCellValue("很好");
                } else if (serviceFeedback.getTag01() == 2) {
                    cell7.setCellValue("良好");
                } else {
                    cell7.setCellValue("一般");
                }
                cell7.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(4, 15 * 256);

            Cell cell8 = row.createCell(5);
            if (serviceFeedback.getTag02() != null) {
                if (serviceFeedback.getTag02() == 1) {
                    cell8.setCellValue("很好");
                } else if (serviceFeedback.getTag02() == 2) {
                    cell8.setCellValue("良好");
                } else {
                    cell8.setCellValue("一般");
                }
                cell8.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(5, 15 * 256);

            Cell cell9 = row.createCell(6);
            if (serviceFeedback.getTag03() != null) {
                if (serviceFeedback.getTag03() == 1) {
                    cell9.setCellValue("很好");
                } else if (serviceFeedback.getTag03() == 2) {
                    cell9.setCellValue("良好");
                } else {
                    cell9.setCellValue("一般");
                }
                cell9.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(6, 15 * 256);

            Cell cell4 = row.createCell(7);
            if (serviceFeedback.getSignIn02() != null) {
                if (serviceFeedback.getSignIn02() == 1) {
                    cell4.setCellValue("准时");
                } else if (serviceFeedback.getSignIn02() == 2) {
                    cell4.setCellValue("迟到");
                } else if (serviceFeedback.getSignIn02() == 3) {
                    cell4.setCellValue("请假");
                } else if (serviceFeedback.getSignIn02() == 4) {
                    cell4.setCellValue("缺课");
                } else if (serviceFeedback.getSignIn02() == 5) {
                    cell4.setCellValue("调课");
                } else if (serviceFeedback.getSignIn02() == 6) {
                    cell4.setCellValue("请假（已补课）");
                } else {
                    cell4.setCellValue("缺课（已补课）");
                }
                cell4.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(7, 15 * 256);

            Cell cell5 = row.createCell(8);
            if (serviceFeedback.getTag05() != null) {
                if (serviceFeedback.getTag05() == 1) {
                    cell5.setCellValue("很好");
                } else if (serviceFeedback.getTag05() == 2) {
                    cell5.setCellValue("良好");
                } else {
                    cell5.setCellValue("一般");
                }
                cell5.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(8, 15 * 256);

            Cell cell61 = row.createCell(9);
            if (serviceFeedback.getTag05() != null) {
                if (serviceFeedback.getTag05() == 1) {
                    cell61.setCellValue("很好");
                } else if (serviceFeedback.getTag05() == 2) {
                    cell61.setCellValue("良好");
                } else {
                    cell61.setCellValue("一般");
                }
                cell61.setCellStyle(cellStyle);
            }
            sheet.setColumnWidth(9, 15 * 256);

            if ((serviceFeedback.getShowPassNum02() != null)) {
                Cell cell10 = row.createCell(10);
                cell10.setCellValue(serviceFeedback.getShowPassNum02());
                sheet.setColumnWidth(10, 15 * 256);
                cell10.setCellStyle(cellStyle);
            }

            if (serviceFeedback.getPassNum02() != null) {
                Cell cell11 = row.createCell(11);
                cell11.setCellValue(serviceFeedback.getPassNum02());
                sheet.setColumnWidth(11, 15 * 256);
                cell11.setCellStyle(cellStyle);
            }

            Cell cell12 = row.createCell(12);
            if (serviceFeedback.getPassNum02() != null) {
                Integer passPercentage = BigDecimal.valueOf(serviceFeedback.getPassNum02()).divide(BigDecimal.valueOf(serviceFeedback.getShowPassNum02()), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).intValue();
                if (passPercentage != null && passPercentage >= 100) {
                    cell12.setCellValue("100%");
                } else {
                    cell12.setCellValue(passPercentage + "%");
                }
            }
            cell12.setCellStyle(cellStyle);
            sheet.setColumnWidth(12, 15 * 256);


            if ((serviceFeedback.getShowPassNum01() != null)) {
                Cell cell10 = row.createCell(13);
                cell10.setCellValue(serviceFeedback.getShowPassNum01());
                sheet.setColumnWidth(13, 15 * 256);
                cell10.setCellStyle(cellStyle);
            }

            if (serviceFeedback.getPassNum01() != null) {
                Cell cell11 = row.createCell(14);
                cell11.setCellValue(serviceFeedback.getPassNum01());
                sheet.setColumnWidth(14, 15 * 256);
                cell11.setCellStyle(cellStyle);
            }

            Cell cell121 = row.createCell(15);
            if (serviceFeedback.getPassNum01() != null) {
                Integer passPercentage = BigDecimal.valueOf(serviceFeedback.getPassNum01()).divide(BigDecimal.valueOf(serviceFeedback.getShowPassNum01()), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).intValue();
                if (passPercentage != null && passPercentage >= 100) {
                    cell121.setCellValue("100%");
                } else {
                    cell121.setCellValue(passPercentage + "%");
                }
            }
            cell121.setCellStyle(cellStyle);
            sheet.setColumnWidth(15, 15 * 256);

            if (serviceFeedback.getPuchCardList() != null || Objects.nonNull(serviceFeedback.getPuchCardList())) {
                for (ServicePuchCard servicePuchCard : serviceFeedback.getPuchCardList()) {
                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 1) {
                        Cell cell13 = row.createCell(16);
                        if (servicePuchCard.getStatus() == 1) {
                            cell13.setCellValue("已打卡");
                        } else {
                            cell13.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(16, 15 * 256);
                        cell13.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 2) {
                        Cell cell14 = row.createCell(17);
                        if (servicePuchCard.getStatus() == 1) {
                            cell14.setCellValue("已打卡");
                        } else {
                            cell14.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(17, 15 * 256);
                        cell14.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 3) {
                        Cell cell15 = row.createCell(18);
                        if (servicePuchCard.getStatus() == 1) {
                            cell15.setCellValue("已打卡");
                        } else {
                            cell15.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(18, 15 * 256);
                        cell15.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 4) {
                        Cell cell16 = row.createCell(19);
                        if (servicePuchCard.getStatus() == 1) {
                            cell16.setCellValue("已打卡");
                        } else {
                            cell16.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(19, 15 * 256);
                        cell16.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 5) {
                        Cell cell17 = row.createCell(20);
                        if (servicePuchCard.getStatus() == 1) {
                            cell17.setCellValue("已打卡");
                        } else {
                            cell17.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(20, 15 * 256);
                        cell17.setCellStyle(cellStyle);
                    }

                    if (servicePuchCard.getWkNum() != null && servicePuchCard.getWkNum() == 6) {
                        Cell cell18 = row.createCell(21);
                        if (servicePuchCard.getStatus() == 1) {
                            cell18.setCellValue("已打卡");
                        } else {
                            cell18.setCellValue("未打卡");
                        }
                        sheet.setColumnWidth(21, 15 * 256);
                        cell18.setCellStyle(cellStyle);
                    }
                }
            }

            // 课堂检测
            Cell cell23 = row.createCell(22);
            if (serviceFeedback.getTag04() != null) {
                cell23.setCellValue(serviceFeedback.getTag04());
            }
            sheet.setColumnWidth(22, 15 * 256);
            cell23.setCellStyle(cellStyle);

            // 精品课老师反馈
            Cell cell25 = row.createCell(23);
            if (serviceFeedback.getLeaveMsg01() != null) {
                cell25.setCellValue(serviceFeedback.getLeaveMsg01());
            }
            sheet.setColumnWidth(23, 15 * 256);
            cell25.setCellStyle(cellStyle);

            // 刷题班老师反馈
            Cell cell26 = row.createCell(24);
            if (serviceFeedback.getLeaveMsg02() != null) {
                cell26.setCellValue(serviceFeedback.getLeaveMsg02());
            }
            sheet.setColumnWidth(24, 15 * 256);
            cell26.setCellStyle(cellStyle);

            // 经纪老师反馈
            Cell cell27 = row.createCell(25);
            if (serviceFeedback.getLeaveMsg03() != null) {
                cell27.setCellValue(serviceFeedback.getLeaveMsg03());
            }
            sheet.setColumnWidth(25, 15 * 256);
            cell27.setCellStyle(cellStyle);
        }


        String fileName = "数学和物理教学服务反馈" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("查询缺课记录")
    @GetMapping("/lackClassExcel")
    public Result searchScheduling(@RequestParam Map reMap,
                                   @RequestParam(value = "yearClassId", defaultValue = "", required = false) String yearClassId,
                                   @RequestParam(value = "classTypeId", defaultValue = "", required = false) String classTypeId,
                                   @RequestParam(value = "lessonType", defaultValue = "", required = false) String lessonType,
                                   @RequestParam(value = "lessonNum", defaultValue = "", required = false) String lessonNum,
                                   @RequestParam(value = "isRepair", required = false) List<String> isRepairList) {

        Page<LackCourseLog> iPage = new Page<>(-1, -1);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String gradeId = (String) reMap.get("gradeId");
        String schoolDate = (String) reMap.get("schoolDate");
        String studentName = (String) reMap.get("name");
        String teacherId = (String) reMap.get("teacherId");
        String subjectsId = (String) reMap.get("subjectsId");

        QueryWrapper<LackCourseLog> queryWrapper = new QueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "lack_course_log.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "lack_course_log.quarter_num", quarterNum);
        queryWrapper.inSql(StringUtils.isNotBlank(schoolId), "lack_course_log.school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "lack_course_log.grade_id", gradeId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "grade.teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "lack_course_log.subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "grade.lesson_type", lessonType);
        queryWrapper.inSql(StringUtils.isNotBlank(classTypeId), "grade.course_type_id", classTypeId);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "grade.year_class_id", yearClassId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonNum), "lack_course_log.lesson_num", lessonNum);
        queryWrapper.eq("lack_course_log.deleted", 0);

        //未安排
        if (isRepairList.size() > 0) {
            Collections.sort(isRepairList);
            String sql = "(";
            for (String isRepair : isRepairList) {
                if (isRepair.equals("0")) {
                    sql += "(is_repair=" + isRepair + " or (is_repair=2 and repair_end_date_time<='" + LocalDateTime.now().withNano(0) + "'))";
                } else if ("1".equals(isRepair)) {
                    if (isRepairList.contains("0")) {
                        sql += "or";
                    }
                    sql += "(is_repair = 1)";
                } else if ("2".equals(isRepair)) {
                    //0未安排，1，已补课，2已安排
                    if (isRepairList.contains("0") || isRepairList.contains("1")) {
                        sql += "or";
                    }
                    sql += " (is_repair=2 and repair_end_date_time>='" + LocalDateTime.now().withNano(0) + "')";
                }
            }
            sql += ")";
            queryWrapper.apply(sql);
        }

        if (StringUtils.isNotBlank(schoolDate)) {
            queryWrapper.inSql("lack_course_log.id", "select record_course_id from repair_course where school_date ='" + schoolDate + "' and deleted=0");
        }
        if (StringUtils.isNotBlank(studentName)) {
            queryWrapper.inSql("lack_course_log.student_id", "select id from student where name like'%" + studentName + "%' and deleted=0");
        }
        if (this.sourseLeve.equals(2)) {
            queryWrapper.inSql("lack_course_log.grade_id", "select id from grade where teacher_id =" + this.adminId);
        }

        iLackCourseLogService.getLackCourseLog(iPage, queryWrapper);

        Map<Integer, String> yearClassCache = new HashMap<>();

        for (LackCourseLog lackCourseLog : iPage.getRecords()) {
            RepairCourse repairCourse = iRepairCourseService.getById(lackCourseLog.getRepairId());
            if (repairCourse != null) {
                //是否已经补课
                if (repairCourse.getIsSignIn().equals(1)) {
                    RecordCourse recordCourse = iRecordCourseService.getOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                    if (recordCourse != null) {
                        lackCourseLog.setIsRepair(1);
                    }
                }

                if (lackCourseLog.getIsRepair() != 1 && repairCourse.getEndDateTime().isBefore(LocalDateTime.now())) {
                    lackCourseLog.setRepairEndDateTime(null);
                    lackCourseLog.setIsRepair(0);
                } else {
                    lackCourseLog.setRepairEndDateTime(repairCourse.getEndDateTime());
                    if (repairCourse.getStartDateTime() != null && repairCourse.getEndDateTime() != null) {
                        String startDateR = repairCourse.getStartDateTime().toString();
                        startDateR = startDateR.substring(startDateR.length() - 5);
                        String endDateR = repairCourse.getEndDateTime().toString();
                        endDateR = endDateR.substring(endDateR.length() - 5);
                        lackCourseLog.setRepairDateStr(repairCourse.getSchoolDate() + " " + startDateR + "-" + endDateR);
                    }
                }
                if (repairCourse.getStartDateTime() != null && repairCourse.getEndDateTime() != null) {
                    String startDateR = repairCourse.getStartDateTime().toString();
                    startDateR = startDateR.substring(startDateR.length() - 5);
                    String endDateR = repairCourse.getEndDateTime().toString();
                    endDateR = endDateR.substring(endDateR.length() - 5);
                    lackCourseLog.setPassRepairDateStr(repairCourse.getSchoolDate() + " " + startDateR + "-" + endDateR);
                }

                lackCourseLog.setRepairGradeName(repairCourse.getGradeName());
                lackCourseLog.setRepairTeacherName(repairCourse.getTeacherName());
            } else {
                lackCourseLog.setRepairEndDateTime(null);
                lackCourseLog.setIsRepair(0);
            }

            if (lackCourseLog.getSchedulingAlwaysId() != null) {
                //这里是旧版本写法，以后要删除掉
                CourseSchedulingAlways courseSchedulingAlways = courseSchedulingAlwaysMapper.getDate(lackCourseLog.getSchedulingAlwaysId());
                if (courseSchedulingAlways != null) {
                    lackCourseLog.setStartDate(courseSchedulingAlways.getStartDate());
                    lackCourseLog.setEndDate(courseSchedulingAlways.getEndDate());
                    lackCourseLog.setNum(courseSchedulingAlways.getNum());
                } else {
                    CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(lackCourseLog.getSchedulingAlwaysId());
                    if (courseSchedulingDetail != null) {
                        lackCourseLog.setStartDate(courseSchedulingDetail.getSchoolDate());
                        lackCourseLog.setNum(courseSchedulingDetail.getLessonNum());
                        lackCourseLog.setSchoolTime(courseSchedulingDetail.getTimeStart() + " ~ " + courseSchedulingDetail.getTimeEnd());
                    }
                }
            }
            lackCourseLog.setStudentName(iStudentService.getStudentName(lackCourseLog.getStudentId()));

            if (lackCourseLog.getIsRepair() == 0) {
                lackCourseLog.setIsRepairStr("未安排");
            } else if (lackCourseLog.getIsRepair() == 1) {
                lackCourseLog.setIsRepairStr("已补课");
            } else if (lackCourseLog.getIsRepair() == 2) {
                lackCourseLog.setIsRepairStr("已安排");
            }

            if (lackCourseLog.getYearClassId() != null) {
                // 检查缓存中是否存在yearClassCache，如果不存在则进行查询并存入缓存
                if (!yearClassCache.containsKey(lackCourseLog.getYearClassId())) {
                    yearClassCache.put(lackCourseLog.getYearClassId(), CommonUtil.getYearClassNameForId(lackCourseLog.getYearClassId()));
                }
                lackCourseLog.setYearClassStr(yearClassCache.get(lackCourseLog.getYearClassId()));
            }

        }

        ExcelExportHandle.export(response, "缺课记录", iPage.getRecords(), LackCourseLog.class);

        return new Result(Code.GET_OK, null, "导出成功~");
    }

    @ApiOperation("客户管理导出")
    @GetMapping("/enrollCustomerExcel")
    public Result enrollCustomerExcel(@RequestParam Map reMap) {
        IPage<EnrollCustomer> iPage = new Page<>(-1, -1);
        String status = (String) reMap.get("status");
        String name = (String) reMap.get("name");
        String keyType = (String) reMap.get("keyType");
        String keyWords = (String) reMap.get("keyWords");
        String schoolId = (String) reMap.get("schoolId");
        String ids = (String) reMap.get("ids");

        QueryWrapper<EnrollCustomer> enrollCustomerQueryWrapper = new QueryWrapper<>();
        enrollCustomerQueryWrapper.inSql(StringUtils.isNotBlank(ids), "id", ids);
        enrollCustomerQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        enrollCustomerQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        enrollCustomerQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        if (StringUtils.isNotBlank(keyType) && StringUtils.isNotBlank(keyWords)) {
            if (keyType.equals("4")) {
                enrollCustomerQueryWrapper.like("teacher_name", keyWords);
            } else {
                enrollCustomerQueryWrapper.inSql("id", "select customer_id from enroll_data where deleted = 0 and type=" + keyType + " and teacher_name like'%" + keyWords + "%'");
            }
        }
        if (StringUtils.isNotBlank(schoolId)) {
            enrollCustomerQueryWrapper.eq("school_id", schoolId);
        }
        if (!this.adminModel.getIsSuper().equals(1)) {
            enrollCustomerQueryWrapper.eq("teacher_id", this.adminId);
        }

        iEnrollCustomerService.page(iPage, enrollCustomerQueryWrapper);

        for (EnrollCustomer enrollCustomer : iPage.getRecords()) {
            QueryWrapper<EnrollData> enrollDataQueryWrapper = new QueryWrapper<>();
            enrollDataQueryWrapper.eq("customer_id", enrollCustomer.getId());
            List<EnrollData> enrollDataList = iEnrollDataService.list(enrollDataQueryWrapper);
            enrollCustomer.setEnrollDataList(enrollDataList);
            QueryWrapper<EnrollCommunicate> enrollCommunicateQueryWrapper = new QueryWrapper<>();
            enrollCommunicateQueryWrapper.eq("customer_id", enrollCustomer.getId());
            enrollCommunicateQueryWrapper.orderByDesc("created_at");
            List<EnrollCommunicate> enrollCommunicateList = iEnrollCommunicateService.list(enrollCommunicateQueryWrapper);
            enrollCustomer.setEnrollCommunicateList(enrollCommunicateList);

            if (enrollCustomer.getSex() == 0) {
                enrollCustomer.setSexStr("未知");
            } else if (enrollCustomer.getSex() == 1) {
                enrollCustomer.setSexStr("男");
            } else {
                enrollCustomer.setSexStr("女");
            }
            enrollCustomer.setSchoolStr(iOrganizationService.getById(enrollCustomer.getSchoolId()).getName());
            for (EnrollCommunicate enrollCommunicate : enrollCustomer.getEnrollCommunicateList()) {
                enrollCustomer.setContent(enrollCommunicate.getContent());
            }

            if (enrollCustomer.getStatus() == 0) {
                enrollCustomer.setStatusStr("待邀约");
            } else if (enrollCustomer.getStatus() == 1) {
                enrollCustomer.setStatusStr("已邀约");
            } else if (enrollCustomer.getStatus() == 2) {
                enrollCustomer.setStatusStr("已试听");
            } else if (enrollCustomer.getStatus() == 3) {
                enrollCustomer.setStatusStr("已成交");
            } else if (enrollCustomer.getStatus() == 4) {
                enrollCustomer.setStatusStr("未成交");
            }

            for (EnrollData enrollCommunicate : enrollCustomer.getEnrollDataList()) {
                if (enrollCommunicate.getType() == 1) {
                    enrollCustomer.setInvite(enrollCommunicate.getTeacherName());
                } else if (enrollCommunicate.getType() == 2) {
                    enrollCustomer.setAudition(enrollCommunicate.getTeacherName());
                } else if (enrollCommunicate.getType() == 3) {
                    enrollCustomer.setMake(enrollCommunicate.getTeacherName());
                }
            }
        }

        ExcelExportHandle.export(response, "客户管理", iPage.getRecords(), EnrollCustomer.class);

        return new Result(Code.OK, "", "导出成功");
    }

    @ApiOperation("调课/消课，按学员查看")
    @GetMapping("/consumeCourseForStudentExcel")
    public Result consumeCourseForStudentExcel(@RequestParam Map<String, String> reMap) {
        IPage<RecordCourse> iPage = new Page<>(-1, -1);

        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String subjectsId = reMap.get("subjectsId");
        String courseId = reMap.get("courseId");
        String gradeId = reMap.get("gradeId");
        String teacherId = reMap.get("teacherId");
        String studentName = reMap.get("studentName");
        String courseType = reMap.get("courseType");
        String ids = reMap.get("ids");
        String schoolId = reMap.get("schoolId");

        QueryWrapper<RecordCourse> repairCourseQueryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            repairCourseQueryWrapper.between("school_date", startDate, endDate);
        } else if (StringUtils.isNotBlank(startDate)) {
            repairCourseQueryWrapper.ge("school_date", startDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            repairCourseQueryWrapper.le("school_date", endDate);
        }

        if (StringUtils.isNotBlank(schoolId)) {
            repairCourseQueryWrapper.eq("school_id", schoolId);
        } else {
            repairCourseQueryWrapper.in("school_id", this.baseSchoolIdList);
        }

        if (StringUtils.isNotBlank(courseType)) {
            repairCourseQueryWrapper.eq("course_type", courseType);
        } else {
            repairCourseQueryWrapper.in("course_type", 4, 5);
        }

        repairCourseQueryWrapper.inSql(StringUtils.isNotBlank(ids), "id", ids);
        repairCourseQueryWrapper.eq("deleted", 0);
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        repairCourseQueryWrapper.inSql(StringUtils.isNotBlank(courseId), "grade_id", "select id from grade where course_id = " + courseId + " ");
        repairCourseQueryWrapper.inSql(StringUtils.isNotBlank(studentName), "student_id", "select id from student where name like '%" + studentName + "%' ");
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        repairCourseQueryWrapper.orderByAsc("start_date_time");

        iRepairCourseServicel.consumeCourseForStudentExcel(iPage, repairCourseQueryWrapper);

        for (RecordCourse recordCourse : iPage.getRecords()) {
            recordCourse.setTime(recordCourse.getTimeStart() + " - " + recordCourse.getTimeEnd());
            if (recordCourse.getCourseType() == 1) {
                recordCourse.setCourseTypeStr("正常");
            } else if (recordCourse.getCourseType() == 3) {
                recordCourse.setCourseTypeStr("补课");
            } else if (recordCourse.getCourseType() == 4) {
                recordCourse.setCourseTypeStr("调课");
            } else if (recordCourse.getCourseType() == 5) {
                recordCourse.setCourseTypeStr("消课");
            } else if (recordCourse.getCourseType() == 6) {
                recordCourse.setCourseTypeStr("缺课补课");
            }
        }

        ExcelExportHandle.export(response, "调消课按学员导出", iPage.getRecords(), RecordCourse.class);

        return new Result(Code.OK, "", "导出成功");
    }

    @ApiOperation("调课/消课，按班级查看")
    @GetMapping("/consumeCourseForGradeExcel")
    public Result consumeCourseForGradeExcel(@RequestParam Map<String, String> reMap) {
        IPage<CourseSchedulingDetail> iPage = new Page<>(-1, -1);

        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String ids = reMap.get("ids");

        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.between("school_date", startDate, endDate);
        } else if (StringUtils.isNotBlank(startDate)) {
            courseSchedulingDetailQueryWrapper.ge("school_date", startDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.le("school_date", endDate);
        }

        String schoolId = reMap.get("schoolId");
        if (StringUtils.isNotBlank(schoolId)) {
            courseSchedulingDetailQueryWrapper.eq("school_id", schoolId);
        } else {
            courseSchedulingDetailQueryWrapper.in("school_id", this.baseSchoolIdList);
        }

        String subjectsId = reMap.get("subjectsId");
        String courseId = reMap.get("courseId");
        String gradeId = reMap.get("gradeId");
        String teacherId = reMap.get("teacherId");

        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(courseId), "grade_id", "select id from grade where course_id = " + courseId + " ");
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        courseSchedulingDetailQueryWrapper.eq("type", 2);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(ids), "id", ids);

        courseSchedulingDetailQueryWrapper.orderByAsc("start_date_time");
        iCourseSchedulingDetailService.calendarList(iPage, courseSchedulingDetailQueryWrapper);

        List<CourseSchedulingDetailExcel> courseSchedulingDetailExcels = new ArrayList<>();
        for (CourseSchedulingDetail courseSchedulingDetail : iPage.getRecords()) {
            CourseSchedulingDetailExcel excel = new CourseSchedulingDetailExcel();
            excel.setSchoolDate(courseSchedulingDetail.getSchoolDate());
            excel.setTime(courseSchedulingDetail.getTimeStart() + " - " + courseSchedulingDetail.getTimeEnd());
            excel.setGradeName(courseSchedulingDetail.getGradeName());
            excel.setCourseName(courseSchedulingDetail.getCourseName());
            excel.setTeacherName(courseSchedulingDetail.getTeacherName());

            if (courseSchedulingDetail.getType() == 1) {
                excel.setStatusStr("正常");
            } else if (courseSchedulingDetail.getType() == 2) {
                excel.setStatusStr("调课");
            }
            courseSchedulingDetailExcels.add(excel);
        }

        ExcelExportHandle.export(response, "调消课按学员导出", courseSchedulingDetailExcels, CourseSchedulingDetailExcel.class);


        return new Result(Code.OK, "", "导出成功");
    }

    @ApiOperation("排班人数导出")
    @GetMapping("/studentCountExcel")
    public void studentCountExcel(@RequestParam Map reMap) throws IOException {
        String schoolIds = (String) reMap.get("schoolIds");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String classTypeId = (String) reMap.get("classTypeId");
        String status = (String) reMap.get("status");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        List<Student> studentList = iStudentService.getStudentCount(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, Integer.valueOf(status), startDate, endDate);

        for (Student student : studentList) {
            student.setSchoolName(iOrganizationService.getSchoolName(student.getSchoolId()));
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建顶部样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("幼儿");
        headList.add("一年级");
        headList.add("二年级");
        headList.add("三年级");
        headList.add("四年级");
        headList.add("五年级");
        headList.add("六年级");
        headList.add("七年级");
        headList.add("八年级");
        headList.add("九年级");
        headList.add("高一");
        headList.add("高二");
        headList.add("高三");
        headList.add("合计");

        // 存储年级对应的单元格
        Map<String, Integer> columnMapping = new HashMap<>();
        int p = 0;
        // 写入年级，并将时间作为键值保存到columnMapping1中
        Row timeRow2 = sheet.createRow(0);
        for (int j = 1; j < headList.size(); j++) {
            Cell weekdayCell = timeRow2.createCell(j);
            weekdayCell.setCellValue(headList.get(j));
            weekdayCell.setCellStyle(cellStyle);
            String timeKey = headList.get(j);
            columnMapping.put(timeKey, j);
            sheet.setColumnWidth(p++, 8000);
        }

        // 存储校区对应的单元格
        Map<String, Integer> classMapping1 = new HashMap<>();
        int rowIndex1 = 1;
        for (Student student : studentList) {
            //判断是否存在，如果存在就不添加到单元格中
            if (!classMapping1.containsKey(student.getSchoolName())) {
                Row dataRow = sheet.createRow(rowIndex1++);
                int cellIndex = 0;
                Cell classRoomName = dataRow.createCell(cellIndex++);
                classRoomName.setCellValue(student.getSchoolName().toString());
                classRoomName.setCellStyle(cellStyle);
                classMapping1.put(student.getSchoolName().toString(), rowIndex1);

                Row row1 = sheet.getRow(rowIndex1 - 1);
                Cell gradeCell1 = row1.createCell(14);
                gradeCell1.setCellValue(iStudentService.getStudentCountBySchoolId(String.valueOf(student.getSchoolId()), subjectsId, yearPart, quarterNum, classTypeId, Integer.valueOf(status), startDate, endDate));
                gradeCell1.setCellStyle(cellStyle); // 应用样式

                Cell cell1 = row1.createCell(1);
                sheet.setColumnWidth(10, 10 * 256);
                cell1.setCellStyle(cellStyle);
            }
        }

        // 添加人数信息
        for (Student student : studentList) {
            Integer columnIndex1 = classMapping1.get(student.getSchoolName()); //获取对应行单元格
            Row row1 = sheet.getRow(columnIndex1 - 1);
            Cell gradeCell = row1.createCell(student.getYearClassId() + 1);
            gradeCell.setCellValue(student.getCount());//写入学员人数
            gradeCell.setCellStyle(cellStyle); // 应用样式
        }

        /**
         * 列合计
         */
        Row row1 = sheet.createRow(sheet.getLastRowNum() + 1);// 获取最后一条数据的行索引
        Cell cell = row1.createCell(0);
        cell = row1.createCell(0);
        cell.setCellValue("合计");
        sheet.setColumnWidth(0, 15 * 256);
        cell.setCellStyle(cellStyle);

        Integer studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "0", Integer.valueOf(status), startDate, endDate);

        Cell cell1 = row1.createCell(1);
        if (studentCount != null) {
            cell1.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell1.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "1", Integer.valueOf(status), startDate, endDate);
        Cell cell2 = row1.createCell(2);
        if (studentCount != null) {
            cell2.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell2.setCellStyle(cellStyle);


        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "2", Integer.valueOf(status), startDate, endDate);
        Cell cell3 = row1.createCell(3);
        if (studentCount != null) {
            cell3.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell3.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "3", Integer.valueOf(status), startDate, endDate);
        Cell cell4 = row1.createCell(4);
        if (studentCount != null) {
            cell4.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell4.setCellStyle(cellStyle);


        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "4", Integer.valueOf(status), startDate, endDate);
        Cell cell5 = row1.createCell(5);
        if (studentCount != null) {
            cell5.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell5.setCellStyle(cellStyle);


        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "5", Integer.valueOf(status), startDate, endDate);
        Cell cell6 = row1.createCell(6);
        if (studentCount != null) {
            cell6.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell6.setCellStyle(cellStyle);


        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "6", Integer.valueOf(status), startDate, endDate);
        Cell cell7 = row1.createCell(7);
        if (studentCount != null) {
            cell7.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell7.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "7", Integer.valueOf(status), startDate, endDate);
        Cell cell8 = row1.createCell(8);
        if (studentCount != null) {
            cell8.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell8.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "8", Integer.valueOf(status), startDate, endDate);
        Cell cell9 = row1.createCell(9);
        if (studentCount != null) {
            cell9.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell9.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "9", Integer.valueOf(status), startDate, endDate);
        Cell cell10 = row1.createCell(10);
        if (studentCount != null) {
            cell10.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell10.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "10", Integer.valueOf(status), startDate, endDate);
        Cell cell11 = row1.createCell(11);
        if (studentCount != null) {
            cell11.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell11.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "11", Integer.valueOf(status), startDate, endDate);
        Cell cell12 = row1.createCell(12);
        if (studentCount != null) {
            cell12.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell12.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountByYearClassId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, "12", Integer.valueOf(status), startDate, endDate);
        Cell cell14 = row1.createCell(13);
        if (studentCount != null) {
            cell14.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell14.setCellStyle(cellStyle);

        studentCount = iStudentService.getStudentCountBySchoolId(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, Integer.valueOf(status), startDate, endDate);
        Cell cell13 = row1.createCell(14);
        if (studentCount != null) {
            cell13.setCellValue(studentCount);
        }
        sheet.setColumnWidth(10, 15 * 256);
        cell13.setCellStyle(cellStyle);

        sheet.createFreezePane(1, 1); // 冻结首行首列

        String fileName = "排班人数" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();
    }

    @ApiOperation("课程表导出")
    @GetMapping("/classScheduleExcel")
    public void arrangingExcel(@RequestParam(value = "yearPart", defaultValue = "") Integer yearPart,
                               @RequestParam(value = "quarterNum", defaultValue = "") Integer quarterNum,
                               @RequestParam(value = "schoolId", defaultValue = "") Long schoolId,
                               @RequestParam(value = "subjectsId", defaultValue = "") Integer subjectsId,
                               @RequestParam(value = "lessonType", defaultValue = "1") Integer lessonType) {
        // 通过季度判断是否为假期，1为假期（寒假班、暑假班），否则为非假期（春季班、秋季班）
        Integer IsVacation = iDictService.getIsVacation(quarterNum);

        // 导出文件名
        String excelName = "";

        //校区
        Organization organization = iOrganizationService.getById(schoolId);

        //学期
        Dict dict = iDictService.getQuarter(quarterNum);

        //周内上课时间
        List<String> gradeList = iCourseSchedulingService.weekdayExcel(yearPart, quarterNum, schoolId, subjectsId, lessonType, this.sourseLeve, this.adminId);

        /**
         * 教室号
         */
        List<ClassRoom> classRoomList1 = new ArrayList<>();//周内教室号
        List<ClassRoom> classRoomList2 = new ArrayList<>();//星期六教室号
        List<ClassRoom> classRoomList3 = new ArrayList<>();//星期日教室号
        List<ClassRoom> classRoomList4 = new ArrayList<>();//A天教室号
        List<ClassRoom> classRoomList5 = new ArrayList<>();//B天教室号

        /**
         * 上课时间
         */
        List<String> timeList1 = new ArrayList<>();//星期六上课时间
        List<String> timeList2 = new ArrayList<>();//星期天上课时间
        List<SchedulingGrade> timeList3 = new ArrayList<>();//A天上课时间
        List<SchedulingGrade> timeList4 = new ArrayList<>();//B天上课时间


        /**
         * 表头
         */
        List<List<String>> headList = new ArrayList<List<String>>();//总表头集合
        List<String> head0 = new ArrayList<String>();//第一个sheet中的表头
        List<String> head1 = new ArrayList<String>();//第二个sheet中的表头
        String tabHead = "";//表头

        if (IsVacation.equals(1)) {
            /**
             * 寒假班、暑假班
             */

            /**
             * A天
             */
            //班级上课时间
            timeList3 = iGradeService.getGradeListForScheduling(schoolId, subjectsId, yearPart, quarterNum, "A", lessonType, this.sourseLeve, this.adminId);

            //教室号
            classRoomList4 = iClassRoomService.getGradeClassRoomsByName(schoolId, yearPart, quarterNum, "A", lessonType);

            /**
             * B天
             */
            //班级上课时间
            timeList4 = iGradeService.getGradeListForScheduling(schoolId, subjectsId, yearPart, quarterNum, "B", lessonType, this.sourseLeve, this.adminId);

            //教室号
            classRoomList5 = iClassRoomService.getGradeClassRoomsByName(schoolId, yearPart, quarterNum, "B", lessonType);

            if ((timeList3 != null && classRoomList4 != null) || (timeList4 != null && classRoomList5 != null)) {
                tabHead = organization.getName() + yearPart + "年" + dict.getName() + "课程表";
                head0.add(tabHead);
                headList.add(head0); // 将 head0 添加到 headList 中
                excelName = tabHead;
            }
        } else {
            /**
             * 春季班、秋季班
             */

            /**
             * 周内
             */
            //教室号
            classRoomList1 = iClassRoomService.getGradeClassRoomsByName1(schoolId, yearPart, quarterNum, 0, 6, lessonType);

            if (classRoomList1 != null) {
                tabHead = organization.getName() + yearPart + "年" + dict.getName() + "周内课程表";
                head0.add(tabHead); // 将 tabHead 添加到 head0 中
                headList.add(head0); // 将 head0 添加到 headList 中
            }

            /**
             * 星期六
             */
            //班级上课时间
            timeList1 = iGradeService.getSchoolTimeList(schoolId, yearPart, quarterNum, String.valueOf(6), lessonType);
            timeList1.add(0, "周六");

            //教室号
            classRoomList2 = iClassRoomService.getGradeClassRoomsByName(schoolId, yearPart, quarterNum, String.valueOf(6), lessonType);

            /**
             * 星期天
             */
            //班级上课时间
            timeList2 = iGradeService.getSchoolTimeList(schoolId, yearPart, quarterNum, String.valueOf(0), lessonType);
            timeList2.add(0, "周日");

            //教室号
            classRoomList3 = iClassRoomService.getGradeClassRoomsByName(schoolId, yearPart, quarterNum, String.valueOf(0), lessonType);

            if ((timeList1 != null && classRoomList2 != null) || (timeList2 != null && classRoomList3 != null)) {
                tabHead = organization.getName() + yearPart + "年" + dict.getName() + "周末课程表";
                head1.add(tabHead); // 添加 head1 到 head1 列表中
                headList.add(head1); // 将 head1 添加到 headList 中
            }
            excelName = organization.getName() + yearPart + "年" + dict.getName() + "课程表";
        }

        try (Workbook workbook = new XSSFWorkbook()) {
            /**
             * 字体样式
             */
            Font font1 = workbook.createFont();// 创建字体对象
            font1.setBold(true); // 设置字体加粗

            /**
             * 星期样式
             */
            CellStyle cellStyle1 = workbook.createCellStyle();// 创建样式对象
            cellStyle1.setFont(font1);// 将字体应用于样式
            cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            cellStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle1.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());// 设置前景色为浅黄色

            /**
             * 英语课程样式
             */
            CellStyle cellStyle2 = workbook.createCellStyle();// 创建样式对象
            cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle2.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());// 设置前景色为浅紫色

            /**
             * 数学课程样式
             */
            CellStyle cellStyle4 = workbook.createCellStyle();// 创建样式对象
            cellStyle4.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            cellStyle4.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle4.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());// 设置前景色为浅蓝色

            /**
             * 时间样式
             */
            CellStyle cellStyle3 = workbook.createCellStyle();// 创建样式对象
            cellStyle3.setFont(font1);// 将字体应用于样式
            cellStyle3.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle3.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            cellStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle3.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 设置前景色为浅灰色

            if (IsVacation.equals(1)) {
                /**
                 * 假期
                 */
                for (int i = 0; i < headList.size(); i++) {
                    List<String> head = headList.get(i);
                    String sheetName = head.get(0);
                    Sheet sheet = workbook.createSheet(sheetName);
                    Row row = sheet.createRow(0);

                    // 创建表头，并将每个表头合并为6个单元格
                    Font font2 = workbook.createFont();// 创建字体对象
                    font2.setBold(true); // 设置字体加粗
                    CellStyle style = workbook.createCellStyle();//工作簿样式
                    font2.setFontHeightInPoints((short) 18); // 设置字号为18
                    style.setFont(font1);// 将字体应用于样式
                    style.setAlignment(HorizontalAlignment.CENTER);//设置水平对齐
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
                    style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 设置前景色为浅绿色
                    Font font = workbook.createFont();// 创建字体对象
                    font.setBold(true);// 设置字体加粗
                    style.setFont(font);// 将字体应用于样式

                    int startIndex = 0; // 开始合并单元格的索引
                    int endIndex = 6; // 结束合并单元格的索引

                    // 合并6个单元格
                    for (String header : head) {
                        Cell cell = row.createCell(startIndex);
                        cell.setCellValue(header);//写入表头
                        cell.setCellStyle(style); // 应用样式
                        sheet.setColumnWidth(startIndex, 6000); // 设置第一列宽
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, startIndex, endIndex - 1));
                        startIndex = endIndex;
                        endIndex += 6;
                    }

                    /**
                     * A天
                     */
                    // 添加a天信息
                    Row timeRow = sheet.createRow(1);
                    Cell weekdayCell = timeRow.createCell(0);
                    weekdayCell.setCellValue("A天");
                    weekdayCell.setCellStyle(cellStyle1); // 应用样式

                    // 添加时间信息
                    int rowIndex = 1; // 行索引从1开始
                    int cellIndex = 1; // 列索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList3) {
                        Row dataRow = sheet.getRow(rowIndex);
                        if (dataRow == null) {
                            dataRow = sheet.createRow(rowIndex);
                        }
                        Cell timeCell = dataRow.createCell(cellIndex);
                        timeCell.setCellValue(schedulingGrade.getSchoolTime());
                        timeCell.setCellStyle(cellStyle1); // 应用样式
                        sheet.setColumnWidth(cellIndex, 8000); // 设置列宽
                        cellIndex++; // 更新列索引
                    }

                    // 添加教室和课程信息
                    rowIndex = 2; // 行索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList3) {
                        int timeIndex = 1; // 列索引从1开始
                        for (ClassRoom classRoom : classRoomList4) {
                            if (classRoom.getGradeName().equals(schedulingGrade.getName())) {
                                Row dataRow = sheet.getRow(rowIndex);
                                if (dataRow == null) {
                                    dataRow = sheet.createRow(rowIndex);
                                }
                                Cell timeCell = dataRow.getCell(0); // 获取教室单元格
                                if (timeCell == null) {
                                    timeCell = dataRow.createCell(0); // 创建教室单元格
                                }
                                timeCell.setCellValue(classRoom.getName()); //写入教室信息
                                timeCell.setCellStyle(cellStyle3); // 应用样式

                                Cell contentCell = dataRow.createCell(timeIndex);
                                contentCell.setCellValue(schedulingGrade.getName()); //写入课程信息
                                contentCell.setCellStyle(cellStyle2); // 应用样式
                            }
                            timeIndex++; // 更新列索引
                        }
                        rowIndex++; // 更新行索引
                    }

                    /**
                     * B天
                     */
                    // 添加b天信息
                    int lastRowIndex = sheet.getLastRowNum(); // 获取最后一条数据的行索引
                    // 最后一条数据的行数（从1开始）
                    int lastDataIndex = lastRowIndex + 2;
                    Row timeRow1 = sheet.createRow(lastDataIndex);
                    Cell weekdayCell1 = timeRow1.createCell(0);
                    weekdayCell1.setCellValue("B天");
                    weekdayCell1.setCellStyle(cellStyle1); // 应用样式

                    // 添加时间信息
                    rowIndex = lastDataIndex; // 行索引从1开始
                    cellIndex = 1; // 列索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList4) {
                        Row dataRow = sheet.getRow(rowIndex);
                        if (dataRow == null) {
                            dataRow = sheet.createRow(rowIndex);
                        }
                        Cell timeCell = dataRow.createCell(cellIndex);
                        timeCell.setCellValue(schedulingGrade.getSchoolTime());
                        timeCell.setCellStyle(cellStyle1); // 应用样式
                        sheet.setColumnWidth(cellIndex, 8000); // 设置列宽
                        cellIndex++; // 更新列索引
                    }

                    // 添加教室和课程信息
                    rowIndex = lastDataIndex + 1; // 行索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList4) {
                        int timeIndex = 1; // 列索引从1开始
                        for (ClassRoom classRoom : classRoomList5) {
                            if (classRoom.getGradeName().equals(schedulingGrade.getName())) {
                                Row dataRow = sheet.getRow(rowIndex);
                                if (dataRow == null) {
                                    dataRow = sheet.createRow(rowIndex);
                                }
                                Cell timeCell = dataRow.getCell(0); // 获取教室单元格
                                if (timeCell == null) {
                                    timeCell = dataRow.createCell(0); // 创建教室单元格
                                }
                                timeCell.setCellValue(classRoom.getName()); //写入教室信息
                                timeCell.setCellStyle(cellStyle3); // 应用样式

                                Cell contentCell = dataRow.createCell(timeIndex);
                                contentCell.setCellValue(schedulingGrade.getName()); //写入课程信息
                                contentCell.setCellStyle(cellStyle2); // 应用样式
                            }
                            timeIndex++; // 更新列索引
                        }
                        rowIndex++; // 更新行索引
                    }
                }
            } else {
                /**
                 * 非假期
                 */
                for (int i = 0; i < headList.size(); i++) {
                    List<String> head = headList.get(i);
                    String sheetName = head.get(0);
                    Sheet sheet = workbook.createSheet(sheetName);
                    Row row = sheet.createRow(0);

                    // 创建表头，并将每个表头合并为6个单元格
                    Font font2 = workbook.createFont();// 创建字体对象
                    font2.setBold(true); // 设置字体加粗
                    CellStyle style = workbook.createCellStyle();//工作簿样式
                    font2.setFontHeightInPoints((short) 14); // 设置字号为14
                    style.setFont(font2);// 将字体应用于样式
                    style.setAlignment(HorizontalAlignment.CENTER);//设置水平对齐
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
                    style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 设置前景色为浅绿色
                    Font font = workbook.createFont();
                    font.setBold(true);
                    style.setFont(font);

                    int startIndex = 0; // 开始合并单元格的索引
                    int endIndex = 6; // 结束合并单元格的索引

                    for (String header : head) {
                        Cell cell = row.createCell(startIndex);
                        cell.setCellValue(header);//写入表头
                        cell.setCellStyle(style); // 应用样式
                        sheet.setColumnWidth(startIndex, 6000); // 设置第一列宽
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, startIndex, endIndex - 1));
                        startIndex = endIndex;
                        endIndex += 6;
                    }

                    /**
                     * 周内
                     */
                    // 添加时间和星期信息
                    String headCompare1 = head0.toString();
                    headCompare1 = headCompare1.replaceAll("^\\[|]$", "");
                    int p = 0;
                    if (sheetName.equals(headCompare1)) {
                        Row timeRow = sheet.createRow(1);
                        for (int j = 0; j < gradeList.size(); j++) {
                            Cell weekdayCell = timeRow.createCell(j);
                            weekdayCell.setCellValue(gradeList.get(j));//写入时间和星期
                            sheet.setColumnWidth(p++, 8000);
                            weekdayCell.setCellStyle(cellStyle1); // 应用样式
                        }

                        // 存储教室对应的单元格
                        Map<String, Integer> classMapping = new HashMap<>();
                        int rowIndex = 2;
                        for (ClassRoom classRoom : classRoomList1) {
                            if (!classMapping.containsKey(classRoom.getName())) {
                                Row dataRow = sheet.createRow(rowIndex++);
                                int cellIndex = 0;
                                Cell classRoomName = dataRow.createCell(cellIndex++);
                                classRoomName.setCellValue(classRoom.getName().toString());
                                classRoomName.setCellStyle(cellStyle3);
                                classMapping.put(classRoom.getName().toString(), rowIndex);
                            }
                        }

                        // 添加课程信息
                        for (ClassRoom classRoom : classRoomList1) {
                            // 获取课程所属的星期索引
                            Integer columnIndex1 = classMapping.get(classRoom.getName()); //获取对应的行
                            Row row1 = sheet.getRow(columnIndex1 - 1);
                            Cell gradeCell = row1.getCell(Integer.parseInt(classRoom.getWeekDates())); //获取对应的列
                            if (gradeCell == null) {
                                gradeCell = row1.createCell(Integer.parseInt(classRoom.getWeekDates()));
                            }
                            if (gradeCell.getCellType() != CellType.BLANK) {
                                String existingData = gradeCell.getStringCellValue();
                                String newData = existingData + "\n" + classRoom.getGradeName().toString();
                                gradeCell.setCellValue(newData.trim());
                            } else {
                                gradeCell.setCellValue(classRoom.getGradeName().toString());//写入课程名称
                            }
                            if (classRoom.getSubjectsId() == 1) {
                                cellStyle2.setWrapText(true);//设置为自动换行
                                gradeCell.setCellStyle(cellStyle2); // 应用样式
                            } else {
                                cellStyle4.setWrapText(true);//设置为自动换行
                                gradeCell.setCellStyle(cellStyle4); // 应用样式
                            }

                        }
                    }

                    /**
                     * 周末
                     */
                    String headCompare2 = head1.toString();
                    headCompare2 = headCompare2.replaceAll("^\\[|]$", "");
                    if (sheetName.equals(headCompare2)) {
                        /**
                         * 星期六
                         */
                        // 存储时间对应的单元格
                        Map<String, Integer> columnMapping = new HashMap<>();
                        // 写入时间和星期，将时间作为键值保存到columnMapping中
                        int p2 = 0;
                        Row timeRow1 = sheet.createRow(1);
                        for (int j = 0; j < timeList1.size(); j++) {
                            Cell weekdayCell = timeRow1.createCell(j);
                            weekdayCell.setCellValue(timeList1.get(j));
                            weekdayCell.setCellStyle(cellStyle1);
                            columnMapping.put(timeList1.get(j), j);
                            sheet.setColumnWidth(p2++, 8000);
                        }

                        // 存储教室对应的单元格
                        Map<String, Integer> classMapping = new HashMap<>();
                        int rowIndex = 2;

                        for (ClassRoom classRoom : classRoomList2) {
                            if (!classMapping.containsKey(classRoom.getName())) {
                                Row dataRow = sheet.createRow(rowIndex++);
                                int cellIndex = 0;
                                Cell classRoomName = dataRow.createCell(cellIndex++);
                                classRoomName.setCellValue(classRoom.getName().toString());
                                classRoomName.setCellStyle(cellStyle3);
                                classMapping.put(classRoom.getName().toString(), rowIndex);
                            }
                        }

                        // 添加课程信息
                        for (ClassRoom classRoom : classRoomList2) {
                            Integer columnIndex = columnMapping.get(classRoom.getSchoolTime()); //获取对应列单元格
                            Integer columnIndex1 = classMapping.get(classRoom.getName()); //获取对应行单元格
                            Row row1 = sheet.getRow(columnIndex1 - 1);
                            Cell gradeCell = row1.getCell(columnIndex);
                            if (gradeCell == null) {
                                gradeCell = row1.createCell(columnIndex);
                                gradeCell.setCellValue(classRoom.getGradeName().toString());
                            } else {
                                String existingData = gradeCell.getStringCellValue();
                                String newData = existingData + "\n" + classRoom.getGradeName().toString();
                                gradeCell.setCellValue(newData.trim());
                            }
                            if (classRoom.getSubjectsId() == 1) {
                                cellStyle2.setWrapText(true);//设置为自动换行
                                gradeCell.setCellStyle(cellStyle2); // 应用样式
                            } else {
                                cellStyle4.setWrapText(true);//设置为自动换行
                                gradeCell.setCellStyle(cellStyle4); // 应用样式
                            }
                        }


                        /**
                         * 星期天
                         */
                        int lastDataIndex = sheet.getLastRowNum() + 2; // 获取最后一条数据的行索引

                        // 存储时间对应的单元格
                        Map<String, Integer> columnMapping1 = new HashMap<>();
                        int p4 = 0;
                        // 写入时间和星期，并将时间作为键值保存到columnMapping1中
                        Row timeRow2 = sheet.createRow(lastDataIndex);
                        for (int j = 0; j < timeList2.size(); j++) {
                            Cell weekdayCell = timeRow2.createCell(j);
                            weekdayCell.setCellValue(timeList2.get(j));
                            weekdayCell.setCellStyle(cellStyle1);
                            String timeKey = timeList2.get(j);
                            columnMapping1.put(timeKey, j);
                            sheet.setColumnWidth(p4++, 8000);
                        }

                        // 存储教室对应的单元格
                        Map<String, Integer> classMapping1 = new HashMap<>();
                        int rowIndex1 = lastDataIndex + 1;

                        for (ClassRoom classRoom : classRoomList3) {
                            if (!classMapping1.containsKey(classRoom.getName())) {
                                Row dataRow = sheet.createRow(rowIndex1++);
                                int cellIndex = 0;
                                Cell classRoomName = dataRow.createCell(cellIndex++);
                                classRoomName.setCellValue(classRoom.getName().toString());
                                classRoomName.setCellStyle(cellStyle3);
                                classMapping1.put(classRoom.getName().toString(), rowIndex1);
                            }
                        }

                        // 添加课程信息
                        for (ClassRoom classRoom : classRoomList3) {
                            Integer columnIndex = columnMapping1.get(classRoom.getSchoolTime()); //获取对应列单元格
                            Integer columnIndex1 = classMapping1.get(classRoom.getName()); //获取对应行单元格
                            Row row1 = sheet.getRow(columnIndex1 - 1);
                            Cell gradeCell = row1.createCell(columnIndex);
                            if (gradeCell == null) {
                                gradeCell = row1.createCell(columnIndex);
                                gradeCell.setCellValue(classRoom.getGradeName().toString());
                            } else {
                                String existingData = gradeCell.getStringCellValue();
                                String newData = existingData + "\n" + classRoom.getGradeName().toString();
                                gradeCell.setCellValue(newData.trim());
                            }

                            if (classRoom.getSubjectsId() == 1) {
                                cellStyle2.setWrapText(true);//设置为自动换行
                                gradeCell.setCellStyle(cellStyle2); // 应用样式
                            } else {
                                cellStyle4.setWrapText(true);//设置为自动换行
                                gradeCell.setCellStyle(cellStyle4); // 应用样式
                            }
                        }
                    }
                }
            }

            // 导出Excel文件
            String fileName = excelName + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            //response.setContentType("application/vnd.ms-excel");
            //设置zip压缩格式
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

            // 获取输出流
            OutputStream outputStream = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(outputStream);

            // 关闭工作簿
            workbook.close();

            // 刷新流，用于保证先前写入流的字节被传递给操作系统进行写入
            outputStream.flush();

            // 关闭输出流
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/rankingsExcel")
    @ApiOperation("排位进退步详情导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "rankId1", value = "第一个排位名称", dataType = "String"),
            @ApiImplicitParam(name = "rankId2", value = "第二个排位名称", dataType = "String"),
            @ApiImplicitParam(name = "circumstance", value = "进退步情况", required = false, dataType = "String")
    })
    public void rankingsExcel(@RequestParam Map reMap) throws IOException {
        String roleId = (String) reMap.get("roleId");
        String rankId1 = (String) reMap.get("rankId1");
        String rankId2 = (String) reMap.get("rankId2");
        String circumstance = (String) reMap.get("circumstance");
        String teacherId = (String) reMap.get("teacherId");

        QueryWrapper<StaffRankingDetail> queryWrapper = new QueryWrapper<>();
        List rankIdList = new ArrayList<>();

        rankIdList.add(rankId1);
        rankIdList.add(rankId2);

        queryWrapper.eq(StringUtils.isNotBlank(roleId), "role_admin.role_id", roleId).and(wrapper -> rankIdList.forEach(rapper -> wrapper.or(o -> o.eq("staff_ranking_id", rapper))));

        queryWrapper.eq("staff_ranking_detail.deleted", 0);
        queryWrapper.eq("staff_ranking.deleted", 0);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "staff_ranking_detail.staff_id", teacherId);
        queryWrapper.orderByDesc("staff_ranking_detail.staff_id");
        List<StaffRankingDetail> list = iStaffRankingDetailService.listStaffRankingDetail(queryWrapper);

        HashMap<String, HashMap<String, Object>> map = new HashMap<>();

        for (StaffRankingDetail staffRankingDetail : list) {
            String staffId = staffRankingDetail.getStaffId().toString();
            HashMap<String, Object> staffData;
            if (map.containsKey(staffId)) {
                staffData = map.get(staffId);
            } else {
                staffData = new HashMap<>();
                staffData.put("teacher", staffRankingDetail.getStaffName());
                staffData.put("rankNum1", 0);
                staffData.put("rankNum2", 0);
                staffData.put("circumstance", 0);
                staffData.put("change", 0);
                map.put(staffId, staffData);
            }
            if (rankId1 != null && !rankId1.equals("") && staffRankingDetail.getStaffRankingId().equals(Long.valueOf(rankId1))) {
                staffData.put("rankNum1", iStaffRankingDetailService.rankingNum(Long.valueOf(rankId1), staffRankingDetail.getStaffId()));
            } else if (rankId2 != null && !rankId1.equals("") && staffRankingDetail.getStaffRankingId().equals(Long.valueOf(rankId2))) {
                staffData.put("rankNum2", iStaffRankingDetailService.rankingNum(Long.valueOf(rankId2), staffRankingDetail.getStaffId()));
            }
        }

        List<Map<String, Object>> mapList = new ArrayList<>();
        for (HashMap<String, Object> staffData : map.values()) {
            Integer rankNum1 = (Integer) staffData.get("rankNum1");
            Integer rankNum2 = (Integer) staffData.get("rankNum2");
            if (Objects.nonNull(rankNum1) && Objects.nonNull(rankNum2)) {
                if (rankNum1 != 0 && rankNum2 != 0) {
                    Integer rankNum = rankNum1 - rankNum2;
                    staffData.put("change", rankNum);
                    if (rankNum >= 0) {
                        staffData.put("circumstance", 0);
                    } else {
                        staffData.put("circumstance", 1);
                    }
                }
            } else {
                staffData.put("change", 0);
                staffData.put("circumstance", 0);
            }
            //进退步条件判断，0默认，1进步，2退步
            if (circumstance.equals("1")) {
                if ((Integer) staffData.get("circumstance") == 0) {
                    mapList.add(staffData);
                }
            } else if (circumstance.equals("2")) {
                if ((Integer) staffData.get("circumstance") == 1) {
                    mapList.add(staffData);
                }
            } else {
                mapList.add(staffData);
            }
        }

        // 创建Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("排位进退步详情");

        // 创建样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 11); // 设置字体大小为11
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();
        headList.add("姓名");
        headList.add("第一次排名");
        headList.add("第二次排名");
        headList.add("名次变化");

        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(1, 1); // 冻结首行首列
        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(cellStyle); // 设置单元格样式
        }

        int rowIndex = 1;
        for (Map<String, Object> m : mapList) {
            Row dataRow = sheet.createRow(rowIndex++);
            int cellIndex = 0;
            for (String key : headList) {
                Cell cell = dataRow.createCell(cellIndex++);
                if (key.equals("姓名")) {
                    cell.setCellValue((String) m.get("teacher"));
                } else if (key.equals("第一次排名")) {
                    Integer rankNum1 = m.get("rankNum1") != null ? (Integer) m.get("rankNum1") : 0;
                    cell.setCellValue(rankNum1);
                } else if (key.equals("第二次排名")) {
                    Integer rankNum2 = m.get("rankNum2") != null ? (Integer) m.get("rankNum2") : 0;
                    cell.setCellValue(rankNum2);
                } else if (key.equals("名次变化")) {
                    cell.setCellValue((Integer) m.get("change"));
                }
                cell.setCellStyle(cellStyle);
            }
        }

        sheet.setColumnWidth(0, 15 * 256);
        sheet.setColumnWidth(1, 15 * 256);
        sheet.setColumnWidth(2, 15 * 256);
        sheet.setColumnWidth(3, 15 * 256);

        String fileName = "排位进退步详情" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();
    }

    @GetMapping("rankingDetailExcel")
    @ApiOperation("排位详情列表导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffName", value = "员工名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "staffRankingId", value = "排位id", required = false, dataType = "String")
    })
    public void searchRankingDetail(@RequestParam Map reMap) {
        IPage<Staff> page = new Page<>(-1, -1);

        String roleId = (String) reMap.get("roleId");
        String staffName = (String) reMap.get("staffName");
        String staffRankingId = (String) reMap.get("staffRankingId");

        QueryWrapper wrapper = new QueryWrapper<>();

        wrapper.eq(StringUtils.isNotBlank(roleId), "role_admin.role_id", roleId);
        wrapper.like(StringUtils.isNotBlank(staffName), "staff_ranking_detail.staff_name", staffName);
        wrapper.eq(StringUtils.isNotBlank(staffRankingId), "staff_ranking_detail.staff_ranking_id", staffRankingId);
        wrapper.eq("staff_ranking_detail.deleted", 0);
        wrapper.orderByAsc("staff_ranking_detail.ranking_num");
        List<StaffRankingDetail> staffRankingDetails = iStaffRankingDetailService.listRankingData(wrapper, page).getRecords();

        ExcelExportHandle.export(response, "排位详情列表导出", staffRankingDetails, StaffRankingDetail.class);
    }

    @GetMapping("/workingExcel")
    @ApiOperation("工龄导出")
    public void listQueryRanking(@RequestParam Map reMap) {
        String name = (String) reMap.get("name");
        String status = (String) reMap.get("status");
        String role = (String) reMap.get("roleId");

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "staff.`name`", name);
        queryWrapper.eq(StringUtils.isNotBlank(status), "staff.`status`", status);
        queryWrapper.eq(StringUtils.isNotBlank(role), "role_admin.role_id", role);
        queryWrapper.ne("staff.`name`", "111");
        queryWrapper.notLike("staff.name", "前台");
        queryWrapper.notLike("staff.name", "市场部");
        queryWrapper.notLike("staff.name", "总部");
        queryWrapper.isNotNull("`status`");
        queryWrapper.notLike("staff.`name`", "校区");
        queryWrapper.orderByDesc("working");

        List<Staff> staffList = iStaffService.working(queryWrapper);

        for (Staff staff : staffList) {
            if (staff.getLeaveDate() != null && staff.getEntryDate() != null) {
                staff.setDateStr(staff.getEntryDate() + " - " + staff.getLeaveDate());
            } else if (staff.getEntryDate() != null && staff.getLeaveDate() == null && staff.getStatus().getKey() != 2) {
                staff.setDateStr(staff.getEntryDate() + " - 至今");
            }

            Integer days = staff.getWorking();
            if (days != null) {
                if (days != 0) {
                    int years = days / 365; // 计算年份
                    int remainingDays = days % 365; // 计算剩余天数
                    int months = remainingDays / 30; // 计算月份
                    int day = months % 30;
                    if (years == 0) {
                        if (months == 0) {
                            staff.setWorkingStr(remainingDays + "天");
                        } else {
                            staff.setWorkingStr(months + "月" + day + "天");
                        }
                    } else {
                        if (months == 0) {
                            staff.setWorkingStr(years + "年" + months + "月" + remainingDays + "天");
                        } else {
                            staff.setWorkingStr(years + "年" + months + "月" + day + "天");
                        }
                    }
                }
            }

            staff.setStatusStr(staff.getStatus().getValue());
        }
        ExcelExportHandle.export(response, "工龄", staffList, Staff.class);
    }

    @GetMapping("/analyseExcel")
    @ApiOperation("人员分析导出")
    public void staffAnalyse(@RequestParam Map reMap) throws IOException {
        String name = (String) reMap.get("name");
        String year = (String) reMap.get("year");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String roleId = (String) reMap.get("roleId");
        String subjectId = (String) reMap.get("subjectId");

        List<Staff> staffList = iStaffService.staffAnalyse(quarterNum, year, roleId, name, schoolId, subjectId);
        List<HashMap<String, Object>> mapList = new ArrayList<>();

        StringBuffer teacherSb = new StringBuffer();

        Integer staffListCount = staffList.size();

        if (staffList != null && staffListCount != 0) {
            Integer count = 0;
            for (Staff staff : staffList) {
                count++;
                teacherSb.append(staff.getId());
                if (count < staffListCount) {
                    teacherSb.append(",");
                }
            }
        } else {
            teacherSb.append("0");
        }

        String teacherStr = String.valueOf(teacherSb);

        /**
         * 填写的内容显示
         */
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("year_part", year);
        wrapper.eq("quarter_num", quarterNum);
        wrapper.inSql("teacher_id", teacherStr);
        wrapper.inSql(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        wrapper.inSql("(teacher_id, id)", "SELECT teacher_id, MAX(id) FROM `staff_data` GROUP BY teacher_id");
        wrapper.orderByDesc("id");

        List<StaffData> staffDataList = iStaffDataService.list(wrapper);

        /**
         * 工号排名
         */
        wrapper.clear();
        wrapper.eq("year_part", year);
        wrapper.eq("num", quarterNum);
        Quarter quarter = quarterService.getOne(wrapper);
        wrapper.clear();

        wrapper.ge("ranking_date", quarter.getStartDate());
        wrapper.le("ranking_date", quarter.getEndDate());
        wrapper.like(StringUtils.isNotBlank(name), "staff_ranking_detail.staff_name", name);
        wrapper.eq(StringUtils.isNotBlank(year), "DATE_FORMAT(ranking_date,'%Y')", year);
        wrapper.eq("staff_ranking.deleted", 0);
        wrapper.eq("staff_ranking_detail.deleted", 0);
        wrapper.inSql("staff_id", teacherStr);
        List<StaffRankingDetail> staffRankingDetails = iStaffRankingDetailService.staffAnalysis(wrapper);
        Integer rankingCount = iStaffRankingDetailService.staffAnalysis(wrapper).size();


        /**
         * 缴费率
         */
        String quarterNum2 = null;
        List<RenewClassRecord> records2 = new ArrayList<>();
        List<RenewClassRecord> records1 = iRenewClassService.staffAnalysis(schoolId, year, quarterNum, subjectId, teacherStr);
        String quarterNum1 = quarter.getName();
        String startDate1 = String.valueOf(quarter.getStartDate());
        String endDate1 = String.valueOf(quarter.getEndDate());

        wrapper.clear();
        if (quarterNum.equals("1")) {
            wrapper.eq("year_part", Integer.valueOf(year) - 1);
            wrapper.eq("num", 4);
            wrapper.orderByDesc("id");
            wrapper.last("LIMIT 1");
            Quarter previousQuarter = quarterService.getOne(wrapper);
            records2 = iRenewClassService.staffAnalysis(schoolId, String.valueOf(Integer.valueOf(year) - 1), String.valueOf(previousQuarter.getNum()), subjectId, teacherStr);
            quarterNum2 = previousQuarter.getName();
        } else {
            wrapper.eq("year_part", year);
            wrapper.eq("num", Integer.valueOf(quarterNum) - 1);
            Quarter previousQuarter = quarterService.getOne(wrapper);
            records2 = iRenewClassService.staffAnalysis(schoolId, year, String.valueOf(previousQuarter.getNum()), subjectId, teacherStr);
            quarterNum2 = previousQuarter.getName();
        }

        /**
         * 补课人数
         */
        List<RepairLesson> repairLessons = iRecordCourseService.getRepairLesson(schoolId, year, quarterNum, subjectId, teacherStr);
        Map<Long, Integer> repairCountMap = new HashMap<>();
        for (RepairLesson repairLesson : repairLessons) {
            Long teacherId = repairLesson.getTeacherId();
            int allRepairCount = repairLesson.getAllRepairCount();
            repairCountMap.put(teacherId, allRepairCount);
        }

        /**
         * 招生数据
         */
        //邀约
        List<RepairLesson> recruitCount = iRecordCourseService.enrollmentData(schoolId, startDate1, endDate1, subjectId, String.valueOf(1), teacherStr);
        Map<Long, Double> recruitCountMap = new HashMap<>();
        for (RepairLesson lesson : recruitCount) {
            Long teacherId = lesson.getTeacherId();
            Double dealNum = lesson.getDealNum();
            recruitCountMap.put(teacherId, dealNum);
        }

        //试听
        List<RepairLesson> inviteCount = iRecordCourseService.enrollmentData(schoolId, startDate1, endDate1, subjectId, String.valueOf(2), teacherStr);
        Map<Long, Double> inviteCountMap = new HashMap<>();
        for (RepairLesson lesson : inviteCount) {
            Long teacherId = lesson.getTeacherId();
            Double dealNum = lesson.getDealNum();
            inviteCountMap.put(teacherId, dealNum);
        }

        //成交
        List<RepairLesson> concludeCount = iRecordCourseService.enrollmentData(schoolId, startDate1, endDate1, subjectId, String.valueOf(3), teacherStr);
        Map<Long, Double> concludeCountMap = new HashMap<>();
        for (RepairLesson lesson : concludeCount) {
            Long teacherId = lesson.getTeacherId();
            Double dealNum = lesson.getDealNum();
            concludeCountMap.put(teacherId, dealNum);
        }

        //校区
        List<Organization> organizations = iOrganizationService.list();
        Map<Long, String> organizationsMap = new HashMap<>();
        for (Organization organization : organizations) {
            organizationsMap.put(organization.getId(), organization.getName());
        }

        //角色
        List<Role> roles = iRoleService.list();
        Map<Long, String> rolesMap = new HashMap<>();
        for (Role role : roles) {
            rolesMap.put(role.getId(), role.getName());
        }

        /**
         * 安全值
         */
        //小学学段
        List<HashMap<String, Object>> scoreDataList1 = iTranscriptService.securityData(schoolId, subjectId, year, quarterNum, teacherStr, String.valueOf(1));
        //初中学段
        List<HashMap<String, Object>> scoreDataList2 = iTranscriptService.securityData(schoolId, subjectId, year, quarterNum, teacherStr, String.valueOf(2));

        /**
         * 返回数据
         */
        for (Staff staff : staffList) {
            Long teacherId = staff.getId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("teacherId", teacherId);
            hashMap.put("name", staff.getName());
            hashMap.put("subjectsId", staff.getSubjectsId());
            hashMap.put("quarterNum", quarterNum1);
            hashMap.put("year", year);
            hashMap.put("organization", organizationsMap.get(staff.getSchoolId()));
            hashMap.put("role", rolesMap.get(staff.getRoleId()));

            //填写的数据展示
            hashMap.put("advantage", "");
            hashMap.put("advantageCase", "");
            hashMap.put("deficiency", "");
            hashMap.put("deficiencyCase", "");
            hashMap.put("primaryScore", "");
            hashMap.put("highScore", "");
            hashMap.put("combineScore", "");

            Optional<StaffData> staffDataOptional = staffDataList.stream()
                    .filter(staffData -> staffData.getTeacherId().equals(teacherId))
                    .findFirst();

            staffDataOptional.ifPresent(staffData -> {
                hashMap.put("advantage", staffData.getAdvantage());
                hashMap.put("advantageCase", staffData.getAdvantageCase());
                hashMap.put("deficiency", staffData.getDeficiency());
                hashMap.put("deficiencyCase", staffData.getDeficiencyCase());
                hashMap.put("primaryScore", staffData.getPrimaryScore());
                hashMap.put("highScore", staffData.getHighScore());
                hashMap.put("combineScore", staffData.getCombineScore());
            });

            //安全值
            for (HashMap<String, Object> scoreData : scoreDataList1) {
                if (scoreData.get("teacherId").equals(teacherId)) {
                    hashMap.put("scoreData1", scoreData.get("scoreData"));
                }
            }
            for (HashMap<String, Object> scoreData : scoreDataList2) {
                if (scoreData.get("teacherId").equals(teacherId)) {
                    hashMap.put("scoreData2", scoreData.get("scoreData"));
                }
            }

            double scoreData1 = 0;
            double scoreData2 = 0;

            if (hashMap.containsKey("scoreData1")) {
                Object obj1 = hashMap.get("scoreData1");
                if (obj1 instanceof BigDecimal) {
                    scoreData1 = ((BigDecimal) obj1).setScale(2, RoundingMode.HALF_UP).doubleValue();
                } else if (obj1 instanceof Number) {
                    scoreData1 = ((Number) obj1).doubleValue();
                } else {
                    try {
                        scoreData1 = Double.parseDouble(obj1.toString());
                    } catch (NumberFormatException e) {

                    }
                }
            }

            if (hashMap.containsKey("scoreData2")) {
                Object obj2 = hashMap.get("scoreData2");
                if (obj2 instanceof BigDecimal) {
                    scoreData2 = ((BigDecimal) obj2).setScale(2, RoundingMode.HALF_UP).doubleValue();
                } else if (obj2 instanceof Number) {
                    scoreData2 = ((Number) obj2).doubleValue();
                } else {
                    try {
                        scoreData2 = Double.parseDouble(obj2.toString());
                    } catch (NumberFormatException e) {

                    }
                }
            }

            double scoreData3 = (scoreData1 + scoreData2) / 2;
            if (scoreData3 != 0.0) {
                DecimalFormat df = new DecimalFormat("#.00");
                hashMap.put("scoreData3", df.format(scoreData3));
            }

            //排位
            ArrayList<HashMap<String, Object>> staffRankingsArray = new ArrayList<>();
            for (StaffRankingDetail staffRankingDetail : staffRankingDetails) {
                if (staffRankingDetail.getStaffId().equals(teacherId)) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("name", staffRankingDetail.getStaffRankingName());
                    map.put("ranking", staffRankingDetail.getRankingNum());
                    staffRankingsArray.add(map);
                }
            }
            hashMap.put("staffRankings", staffRankingsArray);

            //补课人数
            int repairCount = repairCountMap.getOrDefault(teacherId, 0);
            hashMap.put("repairCount", repairCount);

            //招生数据
            hashMap.put("recruitCount", recruitCountMap.getOrDefault(teacherId, 0.00));
            hashMap.put("inviteCount", inviteCountMap.getOrDefault(teacherId, 0.00));
            hashMap.put("concludeCount", concludeCountMap.getOrDefault(teacherId, 0.00));

            //缴费率
            double totalPercentage1 = 0.0;
            double totalPercentage2 = 0.0;
            int count1 = 0;
            int count2 = 0;

            ArrayList<HashMap<String, Object>> recordsArray = new ArrayList<>();

            for (RenewClassRecord record : records1) {
                if (record.getTeacherId().equals(teacherId)) {
                    double percentage = (double) record.getBigFifteen() / (record.getBigFifteen() + record.getLittleFifteen()) * 100.0;
                    totalPercentage1 += percentage;
                    count1++;
                }
            }
            double averagePercentage1 = count1 > 0 ? totalPercentage1 / count1 : 0.0;

            HashMap<String, Object> recordsMap1 = new HashMap<>();
            recordsMap1.put("record", averagePercentage1);
            recordsMap1.put("quarterNum", quarterNum1);
            recordsArray.add(recordsMap1);

            for (RenewClassRecord record : records2) {
                if (record.getTeacherId().equals(teacherId)) {
                    double percentage = (double) record.getBigFifteen() / (record.getBigFifteen() + record.getLittleFifteen()) * 100.0;
                    totalPercentage2 += percentage;
                    count2++;
                }
            }
            double averagePercentage2 = count2 > 0 ? totalPercentage2 / count2 : 0.0;
            double averagePercentage = (averagePercentage1 + averagePercentage2) / 2;
            hashMap.put("record1", averagePercentage1);
            hashMap.put("record2", averagePercentage2);
            hashMap.put("record", averagePercentage);
            mapList.add(hashMap);
        }


        // 创建Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(year + "人员分析");

        // 创建样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 11); // 设置字体大小为11
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 第一行
        Row headerRow1 = sheet.createRow(0);
        // 第二行
        Row headerRow2 = sheet.createRow(1);

        /**
         * 第一块
         */
        CellRangeAddress address1 = new CellRangeAddress(0, 1, 0, 0);
        sheet.addMergedRegion(address1);
        Cell headerCell1 = headerRow1.createCell(0);
        headerCell1.setCellValue("教师");
        headerCell1.setCellStyle(cellStyle);
        sheet.createFreezePane(1, 0); // 冻结首列
        sheet.setColumnWidth(0, 15 * 256);

        CellRangeAddress address2 = new CellRangeAddress(0, 1, 1, 1);
        sheet.addMergedRegion(address2);
        Cell headerCell2 = headerRow1.createCell(1);
        headerCell2.setCellValue("优势");
        headerCell2.setCellStyle(cellStyle);
        sheet.setColumnWidth(1, 40 * 256);

        CellRangeAddress address3 = new CellRangeAddress(0, 1, 2, 2);
        sheet.addMergedRegion(address3);
        Cell headerCell3 = headerRow1.createCell(2);
        headerCell3.setCellValue("案例");
        headerCell3.setCellStyle(cellStyle);
        sheet.setColumnWidth(2, 40 * 256);

        CellRangeAddress address4 = new CellRangeAddress(0, 1, 3, 3);
        sheet.addMergedRegion(address4);
        Cell headerCell4 = headerRow1.createCell(3);
        headerCell4.setCellValue("不足");
        headerCell4.setCellStyle(cellStyle);
        sheet.setColumnWidth(3, 40 * 256);

        CellRangeAddress address5 = new CellRangeAddress(0, 1, 4, 4);
        sheet.addMergedRegion(address5);
        Cell headerCell5 = headerRow1.createCell(4);
        headerCell5.setCellValue("案例");
        headerCell5.setCellStyle(cellStyle);
        sheet.setColumnWidth(4, 40 * 256);

        /**
         * 第二块
         */
        CellRangeAddress address6 = new CellRangeAddress(0, 0, 5, 7);
        sheet.addMergedRegion(address6);
        Cell headerCell6 = headerRow1.createCell(5);
        headerCell6.setCellValue("专业测评");
        headerCell6.setCellStyle(cellStyle);

        CellRangeAddress address7 = new CellRangeAddress(0, 0, 8, 10);
        sheet.addMergedRegion(address7);
        Cell headerCell7 = headerRow1.createCell(8);
        headerCell7.setCellValue("期中安全值");
        headerCell7.setCellStyle(cellStyle);

        CellRangeAddress address8 = new CellRangeAddress(0, 0, 11, 13);
        sheet.addMergedRegion(address8);
        Cell headerCell8 = headerRow1.createCell(11);
        headerCell8.setCellValue("缴费率");
        headerCell8.setCellStyle(cellStyle);

        CellRangeAddress address9 = new CellRangeAddress(0, 0, 14, 16);
        sheet.addMergedRegion(address9);
        Cell headerCell9 = headerRow1.createCell(14);
        headerCell9.setCellValue("招生数据");
        headerCell9.setCellStyle(cellStyle);

        if (rankingCount != null && rankingCount > 1) {
            CellRangeAddress address10 = new CellRangeAddress(0, 0, 17, 16 + rankingCount);//动态值
            sheet.addMergedRegion(address10);
            Cell headerCell10 = headerRow1.createCell(17);
            headerCell10.setCellValue("工号排名");
            headerCell10.setCellStyle(cellStyle);

            CellRangeAddress address11 = new CellRangeAddress(0, 1, rankingCount + 17, rankingCount + 17);//动态值
            sheet.addMergedRegion(address11);
            Cell headerCell11 = headerRow1.createCell(rankingCount + 17);
            headerCell11.setCellValue("补课人数");
            headerCell11.setCellStyle(cellStyle);
            sheet.setColumnWidth(rankingCount + 17, 15 * 256);
        } else {
            Cell cell = headerRow1.createCell(17);
            cell.setCellValue("工号排名");
            sheet.setColumnWidth(17, 15 * 256);
            cell.setCellStyle(cellStyle);

            CellRangeAddress address11 = new CellRangeAddress(0, 1, 18, 18);//动态值
            sheet.addMergedRegion(address11);
            Cell headerCell11 = headerRow1.createCell(18);
            headerCell11.setCellValue("补课人数");
            headerCell11.setCellStyle(cellStyle);
            sheet.setColumnWidth(18, 15 * 256);

        }

        Cell cell = headerRow2.createCell(5);
        cell.setCellValue("小学");
        sheet.setColumnWidth(5, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(6);
        cell.setCellValue("初中");
        sheet.setColumnWidth(6, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(7);
        cell.setCellValue("综合");
        sheet.setColumnWidth(7, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(8);
        cell.setCellValue("小学");
        sheet.setColumnWidth(8, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(9);
        cell.setCellValue("初中");
        sheet.setColumnWidth(9, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(10);
        cell.setCellValue("综合");
        sheet.setColumnWidth(10, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(11);
        cell.setCellValue(quarterNum1);//动态值
        sheet.setColumnWidth(11, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(12);
        cell.setCellValue(quarterNum2);
        sheet.setColumnWidth(12, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(13);
        cell.setCellValue("综合");
        sheet.setColumnWidth(13, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(14);
        cell.setCellValue("邀约");
        sheet.setColumnWidth(14, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(15);
        cell.setCellValue("试听");
        sheet.setColumnWidth(15, 15 * 256);
        cell.setCellStyle(cellStyle);

        cell = headerRow2.createCell(16);
        cell.setCellValue("成交");
        sheet.setColumnWidth(16, 15 * 256);
        cell.setCellStyle(cellStyle);

        int i = 0;
        for (StaffRankingDetail staffRankingDetail : staffRankingDetails) {
            i++;
            cell = headerRow2.createCell(16 + i);
            cell.setCellValue(staffRankingDetail.getStaffRankingName());
            sheet.setColumnWidth(16 + i, 25 * 256);
            cell.setCellStyle(cellStyle);
        }

        // 写入数据行
        int rowNum = 2;

        for (HashMap<String, Object> map : mapList) {
            Row row = sheet.createRow(rowNum++);
            Cell cell1 = row.createCell(0);
            if (map.get("name") != null) {
                cell1.setCellValue(map.get("name").toString());
            } else {
                cell1.setCellValue("");
            }
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            if (map.get("advantage") != null) {
                cell2.setCellValue(map.get("advantage").toString());
            } else {
                cell2.setCellValue("");
            }
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            if (map.get("advantageCase") != null) {
                cell3.setCellValue(map.get("advantageCase").toString());
            } else {
                cell3.setCellValue("");
            }
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(3);
            if (map.get("deficiency") != null) {
                cell4.setCellValue(map.get("deficiency").toString());
            } else {
                cell4.setCellValue("");
            }
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(4);
            if (map.get("deficiencyCase") != null) {
                cell5.setCellValue(map.get("deficiencyCase").toString());
            } else {
                cell5.setCellValue("");
            }
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(5);
            if (map.get("primaryScore") != null) {
                cell6.setCellValue(map.get("primaryScore").toString());
            } else {
                cell6.setCellValue("");
            }
            cell6.setCellStyle(cellStyle);

            Cell cell7 = row.createCell(6);
            if (map.get("highScore") != null) {
                cell7.setCellValue(map.get("highScore").toString());
            } else {
                cell7.setCellValue("");
            }
            cell7.setCellStyle(cellStyle);

            Cell cell8 = row.createCell(7);
            if (map.get("combineScore") != null) {
                cell8.setCellValue(map.get("combineScore").toString());
            } else {
                cell8.setCellValue("");
            }
            cell8.setCellStyle(cellStyle);

            Cell cell9 = row.createCell(8);
            if (map.get("scoreData1") != null) {
                BigDecimal scoreData1Value = new BigDecimal(map.get("scoreData1").toString());
                scoreData1Value = scoreData1Value.setScale(2, RoundingMode.HALF_UP);
                cell9.setCellValue(scoreData1Value.doubleValue());
            } else {
                cell9.setCellValue("");
            }
            cell9.setCellStyle(cellStyle);

            Cell cell10 = row.createCell(9);
            if (map.get("scoreData2") != null) {
                BigDecimal scoreData1Value = new BigDecimal(map.get("scoreData2").toString());
                scoreData1Value = scoreData1Value.setScale(2, RoundingMode.HALF_UP);
                cell10.setCellValue(scoreData1Value.doubleValue());
            } else {
                cell10.setCellValue("");
            }
            cell10.setCellStyle(cellStyle);

            Cell cell11 = row.createCell(10);
            if (map.get("scoreData3") != null) {
                BigDecimal scoreData1Value = new BigDecimal(map.get("scoreData3").toString());
                scoreData1Value = scoreData1Value.setScale(2, RoundingMode.HALF_UP);
                cell11.setCellValue(scoreData1Value.doubleValue());
            } else {
                cell11.setCellValue("");
            }
            cell11.setCellStyle(cellStyle);

            Cell cell12 = row.createCell(11);
            if (map.get("record1") != null && !"".equals(map.get("record1")) && !map.get("record1").toString().equals("NaN")) {
                BigDecimal scoreData1Value = new BigDecimal(map.get("record1").toString());
                scoreData1Value = scoreData1Value.setScale(2, RoundingMode.HALF_UP);
                cell12.setCellValue(scoreData1Value.doubleValue());
            } else {
                cell12.setCellValue("");
            }
            cell12.setCellStyle(cellStyle);

            Cell cell13 = row.createCell(12);
            if (map.get("record2") != null && !"".equals(map.get("record2")) && !map.get("record2").toString().equals("NaN")) {
                BigDecimal scoreData2Value = new BigDecimal(map.get("record2").toString());
                scoreData2Value = scoreData2Value.setScale(2, RoundingMode.HALF_UP);
                cell13.setCellValue(scoreData2Value.doubleValue());
            } else {
                cell13.setCellValue("");
            }
            cell13.setCellStyle(cellStyle);

            Cell cell16 = row.createCell(13);
            if (map.get("record") != null && !"".equals(map.get("record")) && !map.get("record").toString().equals("NaN")) {
                BigDecimal scoreDataValue = new BigDecimal(map.get("record").toString());
                scoreDataValue = scoreDataValue.setScale(2, RoundingMode.HALF_UP);
                cell16.setCellValue(scoreDataValue.doubleValue());
            } else {
                cell16.setCellValue("");
            }
            cell16.setCellStyle(cellStyle);

            Cell cell14 = row.createCell(14);
            if (map.get("recruitCount") != null) {
                cell14.setCellValue(map.get("recruitCount").toString());
            } else {
                cell14.setCellValue("");
            }
            cell14.setCellStyle(cellStyle);

            Cell cell15 = row.createCell(15);
            if (map.get("inviteCount") != null) {
                cell15.setCellValue(map.get("inviteCount").toString());
            } else {
                cell15.setCellValue("");
            }
            cell15.setCellStyle(cellStyle);

            Cell cell18 = row.createCell(16);
            if (map.get("concludeCount") != null) {
                cell18.setCellValue(map.get("concludeCount").toString());
            } else {
                cell18.setCellValue("");
            }
            cell18.setCellStyle(cellStyle);

            ArrayList<HashMap<String, Object>> staffRankings = (ArrayList<HashMap<String, Object>>) map.get("staffRankings");
            Map<String, Cell> cellMap = new HashMap<>();
            int i1 = 0;
            if (staffRankings != null) {
                for (HashMap<String, Object> staffRanking : staffRankings) {
                    i1++;
                    int ranking = (int) staffRanking.get("ranking");
                    String name1 = staffRanking.get("name").toString();
                    Cell cellNew = row.createCell(16 + i1);
                    cellNew.setCellValue(ranking);
                    cellNew.setCellStyle(cellStyle);
                    cellMap.put(name1, cellNew);
                }
            }

            Cell cell17;
            if (rankingCount != null) {
                cell17 = row.createCell(rankingCount + 17);
            } else {
                cell17 = row.createCell(17);
            }
            if (map.get("repairCount") != null) {
                cell17.setCellValue(map.get("repairCount").toString());
            } else {
                cell17.setCellValue("");
            }
            cell17.setCellStyle(cellStyle);
        }

        String fileName = "人员分析导出" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();
    }

    @ApiOperation("转校学员列表导出")
    @GetMapping("/changeSchoolStudentsExcel")
    public void changeSchoolStudentsExcel(@RequestParam Map reMap) throws IOException {
        IPage<OrderDetail> iPage = new Page<>(-1, -1);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String yearClassId = (String) reMap.get("yearClassId");
        String subjectsId = (String) reMap.get("subjectsId");
        String teacherId = (String) reMap.get("teacherId");
        String gradeId = (String) reMap.get("gradeId");
        String studentName = (String) reMap.get("studentName");
        String ids = (String) reMap.get("ids");

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.inSql(StringUtils.isNotBlank(ids), "o.id", ids);
        wrapper.eq("o.lesson_type", 1);
        wrapper.gt("o.residue_course_count", 0);
        wrapper.eq("o.year_part", yearPart);
        wrapper.eq("o.quarter_num", quarterNum);
        wrapper.eq(StringUtils.isNotBlank(yearClassId), "o.year_class_id", yearClassId);
        wrapper.eq(StringUtils.isNotBlank(schoolId), "o.school_id", schoolId);
        wrapper.eq(StringUtils.isNotBlank(subjectsId), "o.subjects_id", subjectsId);
        wrapper.eq(StringUtils.isNotBlank(gradeId), "o.grade_id", gradeId);
        wrapper.eq(StringUtils.isNotBlank(teacherId), "g.teacher_id", teacherId);
        wrapper.like(StringUtils.isNotBlank(studentName), "s.`name`", studentName);
        wrapper.notInSql("o.student_id", "SELECT change_school_detail.student_id FROM change_school_detail LEFT JOIN change_school ON change_school_detail.change_school_id = change_school.id WHERE change_school.`status` = 0 AND change_school_detail.subjects_id = o.subjects_id AND change_school.year_part =" + yearPart + " AND change_school.quarter_num =" + quarterNum);
        wrapper.groupBy("student_id,subjects_id,school_id");

        orderDetailMapper.changeSchoolStudents(iPage, wrapper);

        List<Map<String, Object>> mapList = new ArrayList<>();
        for (OrderDetail orderDetail : iPage.getRecords()) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("studentName", orderDetail.getStudentName());
            hashMap.put("yearClassId", CommonUtil.getYearClassNameForId(orderDetail.getYearClassId()));
            hashMap.put("subjectsId", CommonUtil.getSubjectsNameForId(Math.toIntExact(orderDetail.getSubjectsId())));
            hashMap.put("teacherName", orderDetail.getTeacherName());
            hashMap.put("gradeName", orderDetail.getGradeName());
            hashMap.put("readingStatus", orderDetail.getReadingStatus().getValue());
            hashMap.put("schoolName", orderDetail.getSchoolName());
            mapList.add(hashMap);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建顶部样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();
        headList.add("学员姓名");
        headList.add("年级");
        headList.add("科目");
        headList.add("教师");
        headList.add("班级");
        headList.add("学员状态");
        headList.add("校区");

        // 写入表头
        int columnCount = headList.size();

        for (int i = 0; i < columnCount; i++) {
            Row headerRow = sheet.createRow(0);
            for (int j = 0; j < headList.size(); j++) {
                Cell headerCell = headerRow.createCell(j);
                headerCell.setCellValue(headList.get(j));
                headerCell.setCellStyle(cellStyle); // 设置单元格样式
            }
        }

        // 创建顶部样式
        CellStyle cellStyle1 = workbook.createCellStyle();
        Font font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 11);
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 写入数据行
        int rowNum = 1;
        for (Map<String, Object> map : mapList) {
            Row row = sheet.createRow(rowNum++);
            Cell cell3 = row.createCell(0);
            cell3.setCellValue(String.valueOf(map.get("studentName")));
            sheet.setColumnWidth(0, 20 * 256);
            cell3.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell4 = row.createCell(1);
            cell4.setCellValue(String.valueOf(map.get("yearClassId")));
            sheet.setColumnWidth(1, 20 * 256);
            cell4.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell5 = row.createCell(2);
            cell5.setCellValue(String.valueOf(map.get("subjectsId")));
            sheet.setColumnWidth(2, 20 * 256);
            cell5.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell6 = row.createCell(3);
            if (map.get("teacherName") != null) {
                cell6.setCellValue(String.valueOf(map.get("teacherName")));
            } else {
                cell6.setCellValue("");
            }
            sheet.setColumnWidth(3, 20 * 256);
            cell6.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell7 = row.createCell(4);
            if (map.get("gradeName") != null) {
                cell7.setCellValue(String.valueOf(map.get("gradeName")));
            } else {
                cell7.setCellValue("");
            }

            sheet.setColumnWidth(4, 20 * 256);
            cell7.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell8 = row.createCell(5);
            cell8.setCellValue(String.valueOf(map.get("readingStatus")));
            sheet.setColumnWidth(5, 20 * 256);
            cell8.setCellStyle(cellStyle1); // 设置单元格样式

            Cell cell9 = row.createCell(6);
            cell9.setCellValue(String.valueOf(map.get("schoolName")));
            sheet.setColumnWidth(6, 20 * 256);
            cell9.setCellStyle(cellStyle1); // 设置单元格样式
        }


        String fileName = "学员转校" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();
    }

    @ApiOperation("办理中心导出")
    @GetMapping("getApplyExcel")
    public void getApplyExcel(@RequestParam(value = "idList", defaultValue = "", required = false) String idList,
                              @RequestParam(value = "yearPart", defaultValue = "", required = false) String yearPart,
                              @RequestParam(value = "quarterNum", defaultValue = "", required = false) String quarterNum,
                              @RequestParam(value = "startDate", defaultValue = "", required = false) String startDate,
                              @RequestParam(value = "endDate", defaultValue = "", required = false) String endDate,
                              @RequestParam(value = "orderType", defaultValue = "", required = false) String orderType,
                              @RequestParam(value = "isOwn", defaultValue = "", required = false) String isOwn,
                              @RequestParam(value = "status", defaultValue = "", required = false) String status,
                              @RequestParam(value = "keyType", defaultValue = "", required = false) String keyType,
                              @RequestParam(value = "keyWord", defaultValue = "", required = false) String keyWord,
                              @RequestParam(value = "subjectsId", defaultValue = "", required = false) String subjectsId,
                              @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                              @RequestParam(value = "payTypeList", defaultValue = "") String[] payTypeList,
                              @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                              @RequestParam(value = "lessonType", defaultValue = "", required = false) String lessonType) throws InterruptedException {

        IPage<OrderApply> iPage = new Page<>(-1, -1);

        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(startDate)) {
            queryWrapper.between("handle_date", startDate, endDate);
        }
        queryWrapper.eq(StringUtils.isNotBlank(isOwn), "is_own", isOwn);
        queryWrapper.inSql(StringUtils.isNotBlank(idList), "id", idList);

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
//        queryWrapper.eq(StringUtils.isNotBlank(orderType),"order_type",orderType);

        if (StringUtils.isNotBlank(orderType)) {
            String orderType1 = "";
            String[] orderTypes = orderType.split(",");
            for (String type : orderTypes) {
                if (StringUtils.isNotBlank(type)) {
                    if ("4".equals(type)) {
                        orderType1 += "(order_type = 4 AND (apply_type <> 5 OR apply_type IS NULL )) OR ";
                    }
                    if ("6".equals(type)) {
                        orderType1 += "(order_type = 4 AND apply_type = 5) OR ";
                    }
                    if (!"6".equals(type) && !"4".equals(type)) {
                        orderType1 += "(order_type = " + type + ") OR ";
                    }
                }
            }

            // 去除末尾的"OR"和空格
            if (orderType1.endsWith("OR ")) {
                orderType1 = orderType1.substring(0, orderType1.length() - 4);
            }
            String finalOrderType = orderType1;
            queryWrapper.and(wrapper -> wrapper.apply(finalOrderType));
        }

        if (schoolIdList.length > 0) {
            queryWrapper.in("handle_school_id", schoolIdList);
        } else {
            queryWrapper.in("handle_school_id", this.baseSchoolIdList);
        }

        if (payTypeList.length > 0) {
            String typeStr = String.join(",", payTypeList);
            queryWrapper.inSql("id", "select order_id from order_pay_account where accoun_type in (" + typeStr + ")");
        }

        if (this.sourseLeveEnum.equals(SourseLeveEnum.ONESELF)) {
            queryWrapper.eq("created_id", this.adminId);
        }


        //1学员姓名，2订单号，3课程姓名
        if (keyType.equals("1") && StringUtils.isNotBlank(keyWord)) {
            queryWrapper.like("student_name", keyWord);
        } else if (keyType.equals("2") && StringUtils.isNotBlank(keyWord)) {
            queryWrapper.eq("id", keyWord);
        } else if (keyType.equals("3") && StringUtils.isNotBlank(keyWord)) {
            queryWrapper.inSql("id", "select course_id from order_detail where course_name like('%" + keyWord + "%')");
        } else if (keyType.equals("4") && StringUtils.isNotBlank(keyWord)) {
            queryWrapper.eq("linkman_phone", keyWord);
        } else if (keyType.equals("5") && StringUtils.isNotBlank(keyWord)) {
            queryWrapper.eq("id_card_no", keyWord);
        }
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("created_at");
        orderBy.add("id");
        queryWrapper.orderByDesc(orderBy);
        queryWrapper.eq("deleted", 0);
        if (StringUtils.isNotBlank(subjectsId)) {
            queryWrapper.eq("subjects_id_str", subjectsId);
        }
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        IPage<OrderApply> orderApplyIPage = iOrderApplyService.findAll(iPage, queryWrapper);

        for (OrderApply orderApply : orderApplyIPage.getRecords()) {
            orderApply.setStatusStr(orderApply.getStatus().getValue());
            orderApply.setOrderTypeStr(orderApply.getOrderType().getValue());
            if (orderApply.getPayType() == 0) {
                orderApply.setPayTypeStr("未支付");
            } else if (orderApply.getPayType() == 1) {
                orderApply.setPayTypeStr("已支付");
            } else if (orderApply.getPayType() == 2) {
                orderApply.setPayTypeStr("已失效");
            }
        }

        ExcelExportHandle.export(response, "订单表", orderApplyIPage.getRecords(), OrderApply.class);
    }

    @ApiOperation("学员成绩导出")
    @GetMapping("/scoreDataExcel")
    public void scoreDataExcel(@RequestParam Map reMap) throws IOException {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String yearClassId = (String) reMap.get("yearClassId");
        String subjectsId = (String) reMap.get("subjectsId");
        String examNum = (String) reMap.get("examNum");
        String include = (String) reMap.get("include");
        String type = (String) reMap.get("type");
        String gradeSection = (String) reMap.get("gradeSection");
        String courseTypeId = (String) reMap.get("courseTypeId");
        String dataType = (String) reMap.get("dataType");

        List<Long> schoolIdList = this.baseSchoolIdList;
        List<ScoreData> scoreDataList = iTranscriptService.scoreData(schoolId, schoolIdList, subjectsId, yearPart, quarterNum, examNum, gradeSection, yearClassId, type, include, courseTypeId, dataType);

        ScoreData scoreDataAll = new ScoreData();
        scoreDataAll.setStudentAllCount(0);
        scoreDataAll.setStuRealityCount(0);
        scoreDataAll.setNotCounted(0);
        scoreDataAll.setNoPassCount(0);
        scoreDataAll.setPassCount(0);
        scoreDataAll.setCarryCount(0);

        for (ScoreData scoreData : scoreDataList) {
            scoreDataAll.setStudentAllCount(scoreDataAll.getStudentAllCount() + scoreData.getStudentAllCount());
            scoreDataAll.setStuRealityCount(scoreDataAll.getStuRealityCount() + scoreData.getStuRealityCount());
            scoreDataAll.setNotCounted(scoreDataAll.getNotCounted() + scoreData.getNotCounted());
            scoreDataAll.setNoPassCount(scoreDataAll.getNoPassCount() + scoreData.getNoPassCount());
            scoreDataAll.setPassCount(scoreDataAll.getPassCount() + scoreData.getPassCount());
            scoreDataAll.setCarryCount(scoreDataAll.getCarryCount() + scoreData.getCarryCount());
            if (Objects.nonNull(scoreDataAll.getRetrogressCount())) {
                scoreDataAll.setRetrogressCount(scoreDataAll.getRetrogressCount() + scoreData.getRetrogressCount());
            } else {
                scoreDataAll.setRetrogressCount(scoreData.getRetrogressCount());
            }
        }

        if (scoreDataAll.getStuRealityCount() > 0) {
            scoreDataAll.setNoPassRate(new BigDecimal(scoreDataAll.getNoPassCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));//不及格率
            scoreDataAll.setPassRate(new BigDecimal(scoreDataAll.getPassCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));//优秀率
            scoreDataAll.setCarryRate(new BigDecimal(scoreDataAll.getCarryCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP));//优秀率
            scoreDataAll.setSecureRate(new BigDecimal(scoreDataAll.getPassCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).add(new BigDecimal(scoreDataAll.getCarryCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP));//安全值
            scoreDataAll.setRetrogressRate(new BigDecimal(scoreDataAll.getRetrogressCount()).divide(new BigDecimal(scoreDataAll.getStuRealityCount()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));// 退步率
        }

        if (type.equals("1")) {
            scoreDataAll.setTeacherName("合计");
        } else if (type.equals("2")) {
            scoreDataAll.setSchoolName("合计");
        } else if (type.equals("3")) {
            scoreDataAll.setTeacherName("合计");
        } else if (type.equals("4")) {
            scoreDataAll.setSchoolName("合计");
        }

        scoreDataList.add(scoreDataAll);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建顶部样式
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        List<String> headList = new ArrayList<>();

        // 创建顶部样式
        CellStyle cellStyle1 = workbook.createCellStyle();
        Font font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 11);
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

        // 写入数据行
        int rowNum = 1;

        if (type.equals("1")) {
            headList.add("任课老师");
            headList.add("总人数");
            headList.add("实际统计");
            headList.add("未统计");
            headList.add("不及格人数");
            headList.add("优秀人数");
            headList.add("提分人数");
            headList.add("退步人数");
            headList.add("退步率");
            headList.add("不及格率");
            headList.add("优秀率");
            headList.add("提分率");
            headList.add("安全值");

            for (ScoreData scoreDataExcel : scoreDataList) {
                Row row = sheet.createRow(rowNum++);
                Cell cell1 = row.createCell(0);
                cell1.setCellValue(scoreDataExcel.getTeacherName());
                sheet.setColumnWidth(0, 15 * 256);
                cell1.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(scoreDataExcel.getStudentAllCount());
                sheet.setColumnWidth(1, 10 * 256);
                cell2.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(scoreDataExcel.getStuRealityCount());
                sheet.setColumnWidth(2, 10 * 256);
                cell3.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell4 = row.createCell(3);
                cell4.setCellValue(scoreDataExcel.getNotCounted());
                sheet.setColumnWidth(3, 10 * 256);
                cell4.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell5 = row.createCell(4);
                cell5.setCellValue(scoreDataExcel.getNoPassCount());
                sheet.setColumnWidth(4, 10 * 256);
                cell5.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell6 = row.createCell(5);
                cell6.setCellValue(scoreDataExcel.getPassCount());
                sheet.setColumnWidth(5, 10 * 256);
                cell6.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell7 = row.createCell(6);
                cell7.setCellValue(scoreDataExcel.getCarryCount());
                sheet.setColumnWidth(6, 10 * 256);
                cell7.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell8 = row.createCell(7);
                cell8.setCellValue(scoreDataExcel.getRetrogressCount());
                sheet.setColumnWidth(7, 10 * 256);
                cell8.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell9 = row.createCell(8);
                cell9.setCellValue(scoreDataExcel.getRetrogressRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(8, 15 * 256);
                cell9.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell10 = row.createCell(9);
                cell10.setCellValue(scoreDataExcel.getNoPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(9, 15 * 256);
                cell10.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell11 = row.createCell(10);
                cell11.setCellValue(scoreDataExcel.getPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(10, 15 * 256);
                cell11.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell12 = row.createCell(11);
                cell12.setCellValue(scoreDataExcel.getCarryRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(11, 15 * 256);
                cell12.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell13 = row.createCell(12);
                cell13.setCellValue(scoreDataExcel.getSecureRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(12, 15 * 256);
                cell13.setCellStyle(cellStyle1); // 设置单元格样式
            }

        } else if (type.equals("2")) {
            headList.add("校区");
            headList.add("任课老师");
            headList.add("总人数");
            headList.add("实际统计");
            headList.add("未统计");
            headList.add("不及格人数");
            headList.add("优秀人数");
            headList.add("提分人数");
            headList.add("退步人数");
            headList.add("不及格率");
            headList.add("不及格率");
            headList.add("优秀率");
            headList.add("提分率");
            headList.add("安全值");

            for (ScoreData scoreDataExcel : scoreDataList) {
                Row row = sheet.createRow(rowNum++);
                Cell cell = row.createCell(0);
                cell.setCellValue(scoreDataExcel.getSchoolName());
                sheet.setColumnWidth(0, 15 * 256);
                cell.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(scoreDataExcel.getTeacherName());
                sheet.setColumnWidth(1, 15 * 256);
                cell1.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(scoreDataExcel.getStudentAllCount());
                sheet.setColumnWidth(2, 10 * 256);
                cell2.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell3 = row.createCell(3);
                cell3.setCellValue(scoreDataExcel.getStuRealityCount());
                sheet.setColumnWidth(3, 10 * 256);
                cell3.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(scoreDataExcel.getNotCounted());
                sheet.setColumnWidth(4, 10 * 256);
                cell4.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(scoreDataExcel.getNoPassCount());
                sheet.setColumnWidth(5, 10 * 256);
                cell5.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell6 = row.createCell(6);
                cell6.setCellValue(scoreDataExcel.getPassCount());
                sheet.setColumnWidth(6, 10 * 256);
                cell6.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell7 = row.createCell(7);
                cell7.setCellValue(scoreDataExcel.getCarryCount());
                sheet.setColumnWidth(7, 10 * 256);
                cell7.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell8 = row.createCell(8);
                cell8.setCellValue(scoreDataExcel.getRetrogressCount());
                sheet.setColumnWidth(8, 10 * 256);
                cell8.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell9 = row.createCell(9);
                cell9.setCellValue(scoreDataExcel.getRetrogressRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(9, 15 * 256);
                cell9.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell10 = row.createCell(10);
                cell10.setCellValue(scoreDataExcel.getNoPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(10, 15 * 256);
                cell10.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell11 = row.createCell(11);
                cell11.setCellValue(scoreDataExcel.getPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(11, 15 * 256);
                cell11.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell12 = row.createCell(12);
                cell12.setCellValue(scoreDataExcel.getCarryRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(12, 15 * 256);
                cell12.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell13 = row.createCell(13);
                cell13.setCellValue(scoreDataExcel.getSecureRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(13, 15 * 256);
                cell13.setCellStyle(cellStyle1); // 设置单元格样式
            }

        } else if (type.equals("3")) {
            headList.add("校长");
            headList.add("总人数");
            headList.add("实际统计");
            headList.add("未统计");
            headList.add("不及格人数");
            headList.add("优秀人数");
            headList.add("提分人数");
            headList.add("退步人数");
            headList.add("退步率");
            headList.add("不及格率");
            headList.add("优秀率");
            headList.add("提分率");
            headList.add("安全值");

            for (ScoreData scoreDataExcel : scoreDataList) {
                Row row = sheet.createRow(rowNum++);
                Cell cell1 = row.createCell(0);
                cell1.setCellValue(scoreDataExcel.getTeacherName());
                sheet.setColumnWidth(0, 15 * 256);
                cell1.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(scoreDataExcel.getStudentAllCount());
                sheet.setColumnWidth(1, 10 * 256);
                cell2.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(scoreDataExcel.getStuRealityCount());
                sheet.setColumnWidth(2, 10 * 256);
                cell3.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell4 = row.createCell(3);
                cell4.setCellValue(scoreDataExcel.getNotCounted());
                sheet.setColumnWidth(3, 10 * 256);
                cell4.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell5 = row.createCell(4);
                cell5.setCellValue(scoreDataExcel.getNoPassCount());
                sheet.setColumnWidth(4, 10 * 256);
                cell5.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell6 = row.createCell(5);
                cell6.setCellValue(scoreDataExcel.getPassCount());
                sheet.setColumnWidth(5, 10 * 256);
                cell6.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell7 = row.createCell(6);
                cell7.setCellValue(scoreDataExcel.getCarryCount());
                sheet.setColumnWidth(6, 10 * 256);
                cell7.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell8 = row.createCell(7);
                cell8.setCellValue(scoreDataExcel.getRetrogressCount());
                sheet.setColumnWidth(7, 10 * 256);
                cell8.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell9 = row.createCell(8);
                cell9.setCellValue(scoreDataExcel.getRetrogressRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(8, 15 * 256);
                cell9.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell10 = row.createCell(9);
                cell10.setCellValue(scoreDataExcel.getNoPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(9, 15 * 256);
                cell10.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell11 = row.createCell(10);
                cell11.setCellValue(scoreDataExcel.getPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(10, 15 * 256);
                cell11.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell12 = row.createCell(11);
                cell12.setCellValue(scoreDataExcel.getCarryRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(11, 15 * 256);
                cell12.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell13 = row.createCell(12);
                cell13.setCellValue(scoreDataExcel.getSecureRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(12, 15 * 256);
                cell13.setCellStyle(cellStyle1); // 设置单元格样式
            }

        } else if (type.equals("4")) {
            headList.add("校区");
            headList.add("总人数");
            headList.add("实际统计");
            headList.add("未统计");
            headList.add("不及格人数");
            headList.add("优秀人数");
            headList.add("提分人数");
            headList.add("退步人数");
            headList.add("退步率");
            headList.add("不及格率");
            headList.add("优秀率");
            headList.add("提分率");
            headList.add("安全值");

            for (ScoreData scoreDataExcel : scoreDataList) {
                Row row = sheet.createRow(rowNum++);
                Cell cell1 = row.createCell(0);
                cell1.setCellValue(scoreDataExcel.getSchoolName());
                sheet.setColumnWidth(0, 15 * 256);
                cell1.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(scoreDataExcel.getStudentAllCount());
                sheet.setColumnWidth(1, 10 * 256);
                cell2.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(scoreDataExcel.getStuRealityCount());
                sheet.setColumnWidth(2, 10 * 256);
                cell3.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell4 = row.createCell(3);
                cell4.setCellValue(scoreDataExcel.getNotCounted());
                sheet.setColumnWidth(3, 10 * 256);
                cell4.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell5 = row.createCell(4);
                cell5.setCellValue(scoreDataExcel.getNoPassCount());
                sheet.setColumnWidth(4, 10 * 256);
                cell5.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell6 = row.createCell(5);
                cell6.setCellValue(scoreDataExcel.getPassCount());
                sheet.setColumnWidth(5, 10 * 256);
                cell6.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell7 = row.createCell(6);
                cell7.setCellValue(scoreDataExcel.getCarryCount());
                sheet.setColumnWidth(6, 10 * 256);
                cell7.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell8 = row.createCell(7);
                cell8.setCellValue(scoreDataExcel.getRetrogressCount());
                sheet.setColumnWidth(7, 10 * 256);
                cell8.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell9 = row.createCell(8);
                cell9.setCellValue(scoreDataExcel.getRetrogressRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(8, 15 * 256);
                cell9.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell10 = row.createCell(9);
                cell10.setCellValue(scoreDataExcel.getNoPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(9, 15 * 256);
                cell10.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell11 = row.createCell(10);
                cell11.setCellValue(scoreDataExcel.getPassRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(10, 15 * 256);
                cell11.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell12 = row.createCell(11);
                cell12.setCellValue(scoreDataExcel.getCarryRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(11, 15 * 256);
                cell12.setCellStyle(cellStyle1); // 设置单元格样式

                Cell cell13 = row.createCell(12);
                cell13.setCellValue(scoreDataExcel.getSecureRate().setScale(2, RoundingMode.HALF_UP) + "%");
                sheet.setColumnWidth(12, 15 * 256);
                cell13.setCellStyle(cellStyle1); // 设置单元格样式
            }
        }

        // 写入表头
        int columnCount = headList.size();
        for (int i = 0; i < columnCount; i++) {
            Row headerRow = sheet.createRow(0);
            for (int j = 0; j < headList.size(); j++) {
                Cell headerCell = headerRow.createCell(j);
                headerCell.setCellValue(headList.get(j));
                headerCell.setCellStyle(cellStyle); // 设置单元格样式
            }
        }

        String fileName = "成绩数据" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();
    }

    @ApiOperation("退费日报表")
    @GetMapping("/returnPremium")
    public Result returnPremium(@RequestParam Map reMap) {
        IPage<ReturnPremiumDailySheet> iPage = new Page<>(-1, -1);

        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String schoolIdList = (String) reMap.get("schoolIdList");
        String subjectsId = (String) reMap.get("subjectsId");
        String yearClassId = (String) reMap.get("yearClassId");
        String status = (String) reMap.get("status");//校长是否确认 0未确认 1已确认
        String isPrint = (String) reMap.get("isPrint");//是否打印小票 0未打印 1已打印
        String orderType = (String) reMap.get("orderType");// 退费类型 1退费 2转校退费
        String studentName = (String) reMap.get("studentName");
        String teacherId = (String) reMap.get("teacherId");

        iOrderApplyService.getReturnPremiumDailySheet(iPage, orderType, startDate, endDate, schoolIdList, subjectsId, yearClassId, isPrint, studentName, status, teacherId);
        for (ReturnPremiumDailySheet premiumDailySheet : iPage.getRecords()) {
            if (premiumDailySheet.getIsPrint().equals("1")) {
                premiumDailySheet.setIsPrint("已打印");
            } else {
                premiumDailySheet.setIsPrint("未打印");
            }
            premiumDailySheet.setYearClassName(premiumDailySheet.getYearClassId().getValue());
            premiumDailySheet.setSubjectsName(premiumDailySheet.getSubjectsId().getValue());

            // 邀约人
            List<String> inviteNameList = iEnrollInfoService.getEnrollTeacher(premiumDailySheet.getOrderId(), 1);

            // 试听人
            List<String> auditionNameList = iEnrollInfoService.getEnrollTeacher(premiumDailySheet.getOrderId(), 2);

            // 成交人
            List<String> bargainNameList = iEnrollInfoService.getEnrollTeacher(premiumDailySheet.getOrderId(), 3);

            premiumDailySheet.setInviteNames(String.join(",", inviteNameList));
            premiumDailySheet.setAuditionNames(String.join(",", auditionNameList));
            premiumDailySheet.setBargainNames(String.join(",", bargainNameList));
        }
        ExcelExportHandle.export(response, "退费日报表", iPage.getRecords(), ReturnPremiumDailySheet.class);

        return new Result(Code.OK, "", Code.OK_MSG);
    }


    @ApiOperation("需加订导出")
    @GetMapping("/exportNeedOrder")
    public Result exportNeedOrder(
            @RequestParam("yearPart") Integer yearPart,
            @RequestParam("quarterNum") Integer quarterNum,
            @RequestParam("schoolId") Long schoolId,
            @RequestParam("lessonType") Integer lessonType,
            @RequestParam("subjectsId") Long subjectsId,
            @RequestParam(value = "yearClassId", required = false) Integer yearClassId,
            @RequestParam("classTypeId") Long classTypeId,
            @RequestParam(value = "goodsTypeId", required = false, defaultValue = "2") Long goodsTypeId, HttpServletResponse response) throws IOException {

        lessonType = 1;//获取的是精品课所在班级数据
        List<Map<String, Object>> needOrderExportList = iStoreGoodsService.needOrderExport(yearPart, quarterNum, schoolId, lessonType, subjectsId, yearClassId, classTypeId, goodsTypeId);

        int maxLessons = 0;

        for (Map<String, Object> map : needOrderExportList) {
            for (String key : map.keySet()) {
                if (key.startsWith("lessonNum")) {
                    int lessonNumber = Integer.parseInt(key.substring(9));
                    maxLessons = Math.max(maxLessons, lessonNumber);
                }
            }
        }

        // 创建Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("需加订");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("年级");
        headList.add("班型");
        for (int i = 1; i <= maxLessons; i++) {
            headList.add("课次 " + i);
        }

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引

        for (Map<String, Object> map : needOrderExportList) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(map.get("schoolName").toString());
            sheet.setColumnWidth(0, 25 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(map.get("yearClassName").toString());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(map.get("classTypeName").toString());
            sheet.setColumnWidth(2, 15 * 256);
            cell3.setCellStyle(cellStyle);

            for (int i = 1; i <= maxLessons; i++) {
                Cell lessonCell = row.createCell(2 + i);
                Object lessonValue = map.get("lessonNum" + i);
                lessonCell.setCellValue(lessonValue != null ? lessonValue.toString() : "");
                lessonCell.setCellStyle(cellStyle);
                sheet.setColumnWidth(2 + i, 20 * 256);
            }
        }

        String fileName = "需加订" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);
    }

    @ApiOperation("已确认加订")
    @GetMapping("/exportOrderList")
    public Result exportOrderList(@RequestParam("yearPart") Integer yearPart,
                                  @RequestParam("quarterNum") Integer quarterNum,
                                  @RequestParam("schoolId") Long schoolId,
                                  @RequestParam("yearClassId") Integer yearClassId,
                                  @RequestParam("classTypeId") Long classTypeId,
                                  @RequestParam("subjectsId") Long subjectsId,
                                  @RequestParam("lessonType") Integer lessonType,
                                  @RequestParam(value = "goodsTypeId", required = false, defaultValue = "2") Long goodsTypeId,
                                  @RequestParam("status") Integer status,
                                  @RequestParam(value = "type", required = false, defaultValue = "2") Integer type, HttpServletResponse response) throws IOException {
        IPage<OrderApply> iPage = new Page<>(-1, -1);
        QueryWrapper<StoreGoodsOrderBatch> storeGoodsOrderBatchQueryWrapper = new QueryWrapper<>();
        storeGoodsOrderBatchQueryWrapper.eq(schoolId != null, "t1.school_id", schoolId);
        storeGoodsOrderBatchQueryWrapper.eq(yearPart != null, "t1.year_part", yearPart);
        storeGoodsOrderBatchQueryWrapper.eq(quarterNum != null, "t1.quarter_num", quarterNum);
        storeGoodsOrderBatchQueryWrapper.eq(yearClassId != null, "t1.year_class_id", yearClassId);
        storeGoodsOrderBatchQueryWrapper.eq(classTypeId != null, "t1.class_type_id", classTypeId);
        storeGoodsOrderBatchQueryWrapper.eq(subjectsId != null, "t1.subjects_id", subjectsId);
        storeGoodsOrderBatchQueryWrapper.eq(lessonType != null, "t1.lesson_type", lessonType);
        storeGoodsOrderBatchQueryWrapper.eq(goodsTypeId != null, "t1.goods_type_id", goodsTypeId);
        storeGoodsOrderBatchQueryWrapper.eq(status != null, "t1.status", status);
        storeGoodsOrderBatchQueryWrapper.eq(type != null, "t1.type", type);
        storeGoodsOrderBatchQueryWrapper.orderByDesc("t1.id");
        Integer affirmType = 1;//1加订确认，2下单，3入库
        List<Map<String, Object>> exportOrderList = iStoreGoodsOrderBatchService.exportOrderList(iPage, storeGoodsOrderBatchQueryWrapper, affirmType);

        int maxLessons = 0;

        for (Map<String, Object> map : exportOrderList) {
            for (String key : map.keySet()) {
                if (key.startsWith("lessonNum")) {
                    int lessonNumber = Integer.parseInt(key.substring(9));
                    maxLessons = Math.max(maxLessons, lessonNumber);
                }
            }
        }

        // 创建Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("已确认加订");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("年级");
        headList.add("班型");
        for (int i = 1; i <= maxLessons; i++) {
            headList.add("课次 " + i);
        }
        headList.add("确认时间");
        headList.add("状态");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引

        for (Map<String, Object> map : exportOrderList) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(map.get("schoolName").toString());
            sheet.setColumnWidth(0, 25 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(map.get("classYearName").toString());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(map.get("classTypeName").toString());
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            for (int i = 1; i <= maxLessons; i++) {
                Cell lessonCell = row.createCell(2 + i);
                Object lessonValue = map.get("lessonNum" + i);
                lessonCell.setCellValue(lessonValue != null ? lessonValue.toString() : "");
                lessonCell.setCellStyle(cellStyle);
                sheet.setColumnWidth(2 + i, 15 * 256);
            }

            Cell cell5 = row.createCell(3 + maxLessons);
            String affirmTime = map.get("affirmTime").toString().replace("T", " ");
            cell5.setCellValue(affirmTime);
            sheet.setColumnWidth(3 + maxLessons, 30 * 256);
            cell5.setCellStyle(cellStyle);

            if (map.get("status") != null) {
                Cell cell6 = row.createCell(4 + maxLessons);
                if (map.get("status").toString().equals("1")) {
                    cell6.setCellValue("未下单");
                } else if (map.get("status").toString().equals("2")) {
                    cell6.setCellValue("已下单");
                } else if (map.get("status").toString().equals("3")) {
                    cell6.setCellValue("已入库");
                }
                sheet.setColumnWidth(4 + maxLessons, 15 * 256);
                cell6.setCellStyle(cellStyle);
            }
        }

        String fileName = "已确认加订" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);
    }

    @ApiOperation("已下单导出")
    @GetMapping("/exportAlreadyOrder")
    public Result getAlreadyOrder(@RequestParam("yearPart") Integer yearPart,
                                  @RequestParam("quarterNum") Integer quarterNum,
                                  @RequestParam("lessonType") Integer lessonType,
                                  @RequestParam("batchNum") Integer batchNum,
                                  @RequestParam("startDate") String startDate,
                                  @RequestParam("endDate") String endDate) throws IOException {
        IPage<StoreGoodsOrderBatch> iPage = new Page<>(-1, -1);
        QueryWrapper<StoreGoodsOrderBatch> storeGoodsOrderBatchQueryWrapper = new QueryWrapper<>();
        storeGoodsOrderBatchQueryWrapper.eq(yearPart != null, "year_part", yearPart);
        storeGoodsOrderBatchQueryWrapper.eq(quarterNum != null, "quarter_num", quarterNum);
        storeGoodsOrderBatchQueryWrapper.eq(batchNum != null, "batch_num", batchNum);
        storeGoodsOrderBatchQueryWrapper.eq(lessonType != null, "lesson_type", lessonType);
        storeGoodsOrderBatchQueryWrapper.ge(StringUtils.isNotBlank(startDate), "affirm_time", startDate + " 00:00:00");
        storeGoodsOrderBatchQueryWrapper.le(StringUtils.isNotBlank(endDate), "affirm_time", endDate + " 23:59:59");
        storeGoodsOrderBatchQueryWrapper.groupBy("batch_num", "class_type_id", "year_class_id");
        storeGoodsOrderBatchQueryWrapper.orderByDesc("id");

        Integer affirmType = 2;//1加订确认，2下单，3入库
        // 获取批次、年级、班型（list）
        List<StoreGoodsOrderBatch> storeGoodsOrderBatchList = iStoreGoodsOrderBatchService.getAlreadyOrderGroup(iPage, storeGoodsOrderBatchQueryWrapper, affirmType).getRecords();

        QueryWrapper<StoreGoodsOrder> storeGoodsOrderQueryWrapper = new QueryWrapper<>();
        storeGoodsOrderQueryWrapper.eq(yearPart != null, "t1.year_part", yearPart);
        storeGoodsOrderQueryWrapper.eq(quarterNum != null, "t1.quarter_num", quarterNum);
        storeGoodsOrderQueryWrapper.eq(batchNum != null, "t1.batch_num", batchNum);
        storeGoodsOrderQueryWrapper.eq(lessonType != null, "t4.lesson_type", lessonType);
        storeGoodsOrderQueryWrapper.ge(StringUtils.isNotBlank(startDate), "t5.created_at", startDate + " 00:00:00");
        storeGoodsOrderQueryWrapper.le(StringUtils.isNotBlank(endDate), "t5.created_at", endDate + " 23:59:59");

        // 最大课次
        Integer maxLessonNum = iStoreGoodsOrderBatchService.getMaxLessonNum(storeGoodsOrderQueryWrapper, affirmType);

        storeGoodsOrderQueryWrapper.groupBy("t4.class_type_id", "t4.year_class_id", "t4.lesson_num", "t4.lesson_type", "t4.subjects_id");
        // 获取已下单数量（classTypeList）
        List<StoreGoodsOrder> storeGoodsOrderList = iStoreGoodsOrderBatchService.getAlreadyOrder(storeGoodsOrderQueryWrapper, affirmType);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("已下单");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        headList.add("批次");
        headList.add("年级");
        headList.add("班型");
        for (int i = 1; i <= maxLessonNum; i++) {
            headList.add("课次 " + i);
        }
        headList.add("确认时间");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        Map<String, Integer> orderCountMap = new HashMap<>();
        for (StoreGoodsOrder order : storeGoodsOrderList) {
            String key = order.getBatchNum() + "_" + order.getYearClassId() + "_" + order.getClassTypeId() + "_" + order.getLessonNum();
            orderCountMap.put(key, order.getGoodsCount());
        }

        int rowIndex = 1;// 数据行起始索引
        Integer lastBatchNum = null; // 上一个批次名称
        int lastBatchNumRowIndex = 1; // 上一个批次名称的数据行索引，初始化为1

        LocalDateTime lastAffirmTime = null; // 上一个下单时间
        int lastAffirmTimeRowIndex = 1; // 上一个下单时间的数据行索引，初始化为1

        for (StoreGoodsOrderBatch storeGoodsOrder : storeGoodsOrderBatchList) {
            Row row = sheet.createRow(rowIndex);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue("第" + storeGoodsOrder.getBatchNum() + "批");
            sheet.setColumnWidth(0, 20 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(storeGoodsOrder.getYearClassName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(storeGoodsOrder.getClassTypeName());
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            for (int i = 1; i <= maxLessonNum; i++) {
                Cell lessonCell = row.createCell(2 + i);
                String orderKey = storeGoodsOrder.getBatchNum() + "_" + storeGoodsOrder.getYearClassId() + "_" + storeGoodsOrder.getClassTypeId() + "_" + i;
                Integer goodsCount = orderCountMap.getOrDefault(orderKey, 0);
                lessonCell.setCellValue(goodsCount);
                lessonCell.setCellStyle(cellStyle);
                sheet.setColumnWidth(2 + i, 15 * 256);
            }

            Cell cell5 = row.createCell(3 + maxLessonNum);
            String affirmTime = storeGoodsOrder.getAffirmTime().toString().replace("T", " ");
            cell5.setCellValue(affirmTime);
            sheet.setColumnWidth(3 + maxLessonNum, 30 * 256);
            cell5.setCellStyle(cellStyle);

            // 批次合并逻辑
            if (lastBatchNum != null && !storeGoodsOrder.getBatchNum().equals(lastBatchNum)) {
                if (rowIndex - lastBatchNumRowIndex > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(lastBatchNumRowIndex, rowIndex - 1, 0, 0));
                }
                lastBatchNumRowIndex = rowIndex; // 更新为当前数据行索引
            }
            lastBatchNum = storeGoodsOrder.getBatchNum();

            // 下单时间合并逻辑
            if (lastAffirmTime != null && !storeGoodsOrder.getAffirmTime().equals(lastAffirmTime)) {
                if (rowIndex - lastAffirmTimeRowIndex > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(lastAffirmTimeRowIndex, rowIndex - 1, 3 + maxLessonNum, 3 + maxLessonNum));
                }
                lastAffirmTimeRowIndex = rowIndex; // 更新为当前数据行索引
            }
            lastAffirmTime = storeGoodsOrder.getAffirmTime();

            rowIndex++;
        }

        // 处理最后一个批次的合并
        if (rowIndex - lastBatchNumRowIndex > 1) {
            sheet.addMergedRegion(new CellRangeAddress(lastBatchNumRowIndex, rowIndex - 1, 0, 0));
        }
        // 处理最后一个下单时间的合并
        if (rowIndex - lastAffirmTimeRowIndex > 1) {
            sheet.addMergedRegion(new CellRangeAddress(lastAffirmTimeRowIndex, rowIndex - 1, 3 + maxLessonNum, 3 + maxLessonNum));
        }

        String fileName = "已下单" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);
    }

    @ApiOperation("已下单详情导出")
    @GetMapping("/exportAlreadyOrderDetail")
    public Result getAlreadyOrderDetail(@RequestParam("batchNum") Integer batchNum) throws IOException {
        IPage<StoreGoodsOrderBatch> iPage = new Page<>(-1, -1);

        QueryWrapper<StoreGoodsOrderBatch> storeGoodsOrderBatchQueryWrapper = new QueryWrapper<>();
        storeGoodsOrderBatchQueryWrapper.inSql("t1.id", "select t2.goods_order_batch_id from store_goods_batch as t1 INNER JOIN store_goods_batch_detail as t2 on t1.id = t2.goods_batch_id where t1.batch_num =" + batchNum);

        Integer affirmType = 2;//1加订确认，2下单，3入库
        List<StoreGoodsOrderBatch> storeGoodsOrderList = iStoreGoodsOrderBatchService.getListForSearch(iPage, storeGoodsOrderBatchQueryWrapper, affirmType).getRecords();

        int maxLessons = 0;

        List<Map<Integer, Integer>> goodsCountMaps = new ArrayList<>();

        for (StoreGoodsOrderBatch lessons : storeGoodsOrderList) {
            List<StoreGoodsOrder> storeGoodsOrders = lessons.getStoreGoodsOrderList();
            Map<Integer, Integer> goodsCountMap = new HashMap<>();
            for (StoreGoodsOrder goodsOrder : storeGoodsOrders) {
                maxLessons = Math.max(maxLessons, goodsOrder.getLessonNum());
                goodsCountMap.put(goodsOrder.getLessonNum(), goodsOrder.getGoodsCount());
            }
            goodsCountMaps.add(goodsCountMap);
        }

        // 创建Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("已下单详情");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("年级");
        headList.add("班型");
        for (int i = 1; i <= maxLessons; i++) {
            headList.add("课次 " + i);
        }
        headList.add("确认时间");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引

        for (int batchIndex = 0; batchIndex < storeGoodsOrderList.size(); batchIndex++) {
            StoreGoodsOrderBatch storeGoodsOrderBatch = storeGoodsOrderList.get(batchIndex);
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(storeGoodsOrderBatch.getSchoolName());
            sheet.setColumnWidth(0, 25 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(storeGoodsOrderBatch.getYearClassName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(storeGoodsOrderBatch.getClassTypeName());
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Map<Integer, Integer> goodsCountMap = goodsCountMaps.get(batchIndex);
            for (int i = 1; i <= maxLessons; i++) {
                Cell lessonCell = row.createCell(2 + i);
                Integer goodsCount = goodsCountMap.getOrDefault(i, 0);
                lessonCell.setCellValue(goodsCount);
                lessonCell.setCellStyle(cellStyle);
                sheet.setColumnWidth(2 + i, 15 * 256);
            }

            Cell cell5 = row.createCell(3 + maxLessons);
            String affirmTime = storeGoodsOrderBatch.getAffirmTime().toString().replace("T", " ");
            cell5.setCellValue(affirmTime);
            sheet.setColumnWidth(3 + maxLessons, 30 * 256);
            cell5.setCellStyle(cellStyle);
        }

        String fileName = "已下单详情" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", Code.OK_MSG);
    }

    @ApiOperation("库存列表导出")
    @GetMapping("/exportStoreGoodsList")
    public Result exportStoreGoodsList(@RequestParam("yearPart") Integer yearPart,
                                       @RequestParam("quarterNum") Integer quarterNum,
                                       @RequestParam("schoolId") Long schoolId,
                                       @RequestParam("subjectsId") Long subjectsId,
                                       @RequestParam("yearClassId") Integer yearClassId,
                                       @RequestParam("lessonType") Integer lessonType,
                                       @RequestParam("classTypeId") Long classTypeId,
                                       @RequestParam(value = "goodsTypeId", required = false, defaultValue = "2") Long goodsTypeId) throws IOException {
        IPage<OrderApply> iPage = new Page<>(-1, -1);
        // 获取已下单数量（list）
        List<StoreGoods> storeGoodsList = iStoreGoodsService.getStoreGoodsList(yearPart, quarterNum, schoolId, subjectsId, yearClassId, classTypeId, goodsTypeId, lessonType);
        // 获取批次、年级、班型（classTypeList）
        List<CourseType> classTypeList = iStoreGoodsService.getClassTypeList(iPage, yearPart, quarterNum, schoolId, subjectsId, yearClassId, classTypeId, goodsTypeId).getRecords();
        Integer maxLessonNum = iStoreGoodsService.getMaxLessonNum(yearPart, quarterNum, schoolId, subjectsId, yearClassId, classTypeId, goodsTypeId);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("库存查询");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("年级");
        headList.add("班型");
        for (int i = 1; i <= maxLessonNum; i++) {
            headList.add("课次 " + i);
        }

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        Map<String, Integer> orderCountMap = new HashMap<>();
        for (StoreGoods order : storeGoodsList) {
            String key = order.getYearClassId() + "_" + order.getClassTypeId() + "_" + order.getLessonNum();
            orderCountMap.put(key, order.getGoodsCount());
        }

        int rowIndex = 1;// 数据行起始索引

        // todo：设计图改了 待定
//        for (CourseType courseType : classTypeList) {
//            Row row = sheet.createRow(rowIndex++);
//
//            Cell cell1 = row.createCell(0);
//            cell1.setCellValue();//校区
//            sheet.setColumnWidth(0, 20 * 256);
//            cell1.setCellStyle(cellStyle);
//
//            Cell cell2 = row.createCell(1);
//            cell2.setCellValue();//年级
//            sheet.setColumnWidth(1, 15 * 256);
//            cell2.setCellStyle(cellStyle);
//
//            Cell cell3 = row.createCell(2);
//            cell3.setCellValue(courseType.getName());
//            sheet.setColumnWidth(2, 20 * 256);
//            cell3.setCellStyle(cellStyle);
//
//            for (int i = 1; i <= maxLessonNum; i++) {
//                Cell lessonCell = row.createCell(2 + i);
//                String orderKey = courseType.getYearClassId() + "_" + courseType.getId() + "_" + i;
//                Integer goodsCount = orderCountMap.getOrDefault(orderKey, 0);
//                lessonCell.setCellValue(goodsCount);
//                lessonCell.setCellStyle(cellStyle);
//                sheet.setColumnWidth(2 + i, 15 * 256);
//            }
//
//        }

        /**
         * 列合计
         */
        Row row1 = sheet.createRow(sheet.getLastRowNum() + 1);// 获取最后一条数据的行索引
        Cell cell = row1.createCell(0);
        cell = row1.createCell(0);
        cell.setCellValue("合计");
        sheet.setColumnWidth(0, 15 * 256);
        cell.setCellStyle(cellStyle);


        String fileName = "库存查询" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", "");
    }

    @ApiOperation("入库列表导出")
    @GetMapping("/exportAddStoreGoodsLog")
    public Result exportAddStoreGoodsLog(@RequestParam("yearPart") Integer yearPart,
                                         @RequestParam("quarterNum") Integer quarterNum,
                                         @RequestParam("schoolId") Long schoolId,
                                         @RequestParam("yearClassId") Integer yearClassId,
                                         @RequestParam("classTypeId") Long classTypeId,
                                         @RequestParam("subjectsId") Long subjectsId,
                                         @RequestParam("lessonType") Integer lessonType,
                                         @RequestParam(value = "goodsTypeId", required = false, defaultValue = "2") Long goodsTypeId,
                                         @RequestParam(value = "status", required = false, defaultValue = "3") Integer status,
                                         @RequestParam(value = "type", required = false) Integer type) throws IOException {
        IPage<OrderApply> iPage = new Page<>(-1, -1);
        QueryWrapper<StoreGoodsOrderBatch> storeGoodsOrderBatchQueryWrapper = new QueryWrapper<>();

        storeGoodsOrderBatchQueryWrapper.eq(yearPart != null, "t1.year_part", yearPart);
        storeGoodsOrderBatchQueryWrapper.eq(quarterNum != null, "t1.quarter_num", quarterNum);
        storeGoodsOrderBatchQueryWrapper.eq(yearClassId != null, "t1.year_class_id", yearClassId);
        storeGoodsOrderBatchQueryWrapper.eq(classTypeId != null, "t1.class_type_id", classTypeId);
        storeGoodsOrderBatchQueryWrapper.eq(subjectsId != null, "t1.subjects_id", subjectsId);
        storeGoodsOrderBatchQueryWrapper.eq(lessonType != null, "t1.lesson_type", lessonType);
        storeGoodsOrderBatchQueryWrapper.eq(goodsTypeId != null, "t1.goods_type_id", goodsTypeId);
        storeGoodsOrderBatchQueryWrapper.eq(status != null, "t1.status", status);
        storeGoodsOrderBatchQueryWrapper.eq(type != null, "t1.type", type);
        Integer affirmType = 3;//1加订确认，2下单，3入库
        List<StoreGoodsOrderBatch> storeGoodsList = iStoreGoodsOrderBatchService.getListForSearch(iPage, storeGoodsOrderBatchQueryWrapper, affirmType).getRecords();
        Integer maxLessonNum = iStoreGoodsService.getMaxLessonNum(yearPart, quarterNum, schoolId, subjectsId, yearClassId, classTypeId, goodsTypeId);

        List<Map<Integer, Integer>> goodsCountMaps = new ArrayList<>();

        for (StoreGoodsOrderBatch lessons : storeGoodsList) {
            List<StoreGoodsOrder> storeGoodsOrders = lessons.getStoreGoodsOrderList();
            Map<Integer, Integer> goodsCountMap = new HashMap<>();
            for (StoreGoodsOrder goodsOrder : storeGoodsOrders) {
                maxLessonNum = Math.max(maxLessonNum, goodsOrder.getLessonNum());
                goodsCountMap.put(goodsOrder.getLessonNum(), goodsOrder.getGoodsCount());
            }
            goodsCountMaps.add(goodsCountMap);
        }

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("入库记录");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        headList.add("校区");
        headList.add("年级");
        headList.add("班型");
        for (int i = 1; i <= maxLessonNum; i++) {
            headList.add("课次 " + i);
        }
        headList.add("入库时间");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        int rowIndex = 1;// 数据行起始索引

        for (int batchIndex = 0; batchIndex < storeGoodsList.size(); batchIndex++) {
            StoreGoodsOrderBatch storeGoodsOrderBatch = storeGoodsList.get(batchIndex);

            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(storeGoodsOrderBatch.getSchoolName());
            sheet.setColumnWidth(0, 25 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(storeGoodsOrderBatch.getYearClassName());
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(storeGoodsOrderBatch.getClassTypeName());
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Map<Integer, Integer> goodsCountMap = goodsCountMaps.get(batchIndex);
            for (int i = 1; i <= maxLessonNum; i++) {
                Cell lessonCell = row.createCell(2 + i);
                Integer goodsCount = goodsCountMap.getOrDefault(i, 0);
                lessonCell.setCellValue(goodsCount);
                lessonCell.setCellStyle(cellStyle);
                sheet.setColumnWidth(2 + i, 15 * 256);
            }

            Cell cell5 = row.createCell(3 + maxLessonNum);
            String affirmTime = storeGoodsOrderBatch.getAffirmTime().toString().replace("T", " ");
            cell5.setCellValue(affirmTime);
            sheet.setColumnWidth(3 + maxLessonNum, 30 * 256);
            cell5.setCellStyle(cellStyle);
        }

        String fileName = "入库记录" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, "", "");
    }

    @ApiOperation("课时汇总列表导出")
    @GetMapping("/exportClassesNumTotal")
    public Result exportClassesNumTotal(@RequestParam Map reMap) throws IOException {
        Page<ClassesNum> iPage = new Page<>(-1, -1);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String teacherId = (String) reMap.get("teacherId");
        String type = (String) reMap.get("type");//1个人 2校区老师 3校长 4校区
        String isDescOrAsc = (String) reMap.get("isDescOrAsc");//0正序 1倒序
        if (StringUtils.isBlank(isDescOrAsc)) {
            isDescOrAsc = "1";
        }
        String isFieldToSc = (String) reMap.get("isFieldToSc");// 要排序的字段，已上课次：buckleClassHouse，课时费：buckleClassMoney
        if (StringUtils.isBlank(isFieldToSc)) {
            isFieldToSc = "buckleClassHouse";
        }

        List<ClassesNum> classesNumList = iRecordCourseService.classesNumList(iPage, yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, teacherId, type, isDescOrAsc, isFieldToSc).getRecords();

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("课时汇总列表");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        if (type.equals("1")) {
            headList.add("教师");
            headList.add("已上课次");
            headList.add("课时费");

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            int rowIndex = 1;// 数据行起始索引

            for (ClassesNum classesNum : classesNumList) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(classesNum.getTeacherName());
                sheet.setColumnWidth(0, 25 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(classesNum.getBuckleClassHouse());
                sheet.setColumnWidth(1, 15 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(classesNum.getBuckleClassMoney().toString());
                sheet.setColumnWidth(2, 20 * 256);
                cell3.setCellStyle(cellStyle);
            }

        } else if (type.equals("2")) {
            headList.add("校区");
            headList.add("教师");
            headList.add("已上课次");
            headList.add("课时费");

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            int rowIndex = 1;// 数据行起始索引

            for (ClassesNum classesNum : classesNumList) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(classesNum.getSchoolName());
                sheet.setColumnWidth(0, 25 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(classesNum.getTeacherName());
                sheet.setColumnWidth(1, 25 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(classesNum.getBuckleClassHouse());
                sheet.setColumnWidth(2, 15 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(3);
                cell4.setCellValue(classesNum.getBuckleClassMoney().toString());
                sheet.setColumnWidth(3, 20 * 256);
                cell4.setCellStyle(cellStyle);
            }

        } else if (type.equals("3")) {
            headList.add("校长");
            headList.add("已上课次");
            headList.add("课时费");

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            int rowIndex = 1;// 数据行起始索引

            for (ClassesNum classesNum : classesNumList) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(classesNum.getTeacherName());
                sheet.setColumnWidth(0, 25 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(classesNum.getBuckleClassHouse());
                sheet.setColumnWidth(1, 15 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(classesNum.getBuckleClassMoney().toString());
                sheet.setColumnWidth(2, 20 * 256);
                cell3.setCellStyle(cellStyle);
            }

        } else if (type.equals("4")) {
            headList.add("校区");
            headList.add("已上课次");
            headList.add("课时费");

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            int rowIndex = 1;// 数据行起始索引

            for (ClassesNum classesNum : classesNumList) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(classesNum.getSchoolName());
                sheet.setColumnWidth(0, 25 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(classesNum.getBuckleClassHouse());
                sheet.setColumnWidth(1, 15 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(2);
                cell3.setCellValue(classesNum.getBuckleClassMoney().toString());
                sheet.setColumnWidth(2, 20 * 256);
                cell3.setCellStyle(cellStyle);
            }
        }

        String fileName = "课时汇总" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();


        return new Result(Code.GET_OK, "", "导出成功");
    }


    @ApiOperation("课时汇总详情导出")
    @GetMapping("/exportClassesNumDetails")
    public Result classesNumDetails(@RequestParam Map reMap) throws IOException {
        Page<ClassesNum> iPage = new Page<>(-1, -1);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String teacherId = (String) reMap.get("teacherId");

        List<ClassesNum> classesNumDetails = iRecordCourseService.classesNumDetails(iPage, yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, teacherId).getRecords();

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("课时汇总详情");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        headList.add("上课时间");
        headList.add("上课时段");
        headList.add("学员姓名");
        headList.add("班级");
        headList.add("科目");
        headList.add("上课类型");
        headList.add("上课状态");
        headList.add("已消耗课次");
        headList.add("学费消耗");
        headList.add("上课教师");
        headList.add("上课校区");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        int rowIndex = 1;// 数据行起始索引

        for (ClassesNum classesNum : classesNumDetails) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(classesNum.getSchoolDate().toString());
            sheet.setColumnWidth(0, 25 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(classesNum.getTimeStart() + " ~ " + classesNum.getTimeEnd());
            sheet.setColumnWidth(1, 30 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(classesNum.getStudentName());
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(3);
            cell4.setCellValue(classesNum.getGradeName());
            sheet.setColumnWidth(3, 30 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(4);
            cell5.setCellValue(classesNum.getSubjectsName());
            sheet.setColumnWidth(4, 20 * 256);
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(5);
            if (classesNum.getCourseType() != null) {
                if (classesNum.getCourseType() == 1) {
                    cell6.setCellValue("正常");
                } else if (classesNum.getCourseType() == 3) {
                    cell6.setCellValue("补课");
                } else if (classesNum.getCourseType() == 4) {
                    cell6.setCellValue("调课");
                } else if (classesNum.getCourseType() == 5) {
                    cell6.setCellValue("消课");
                } else if (classesNum.getCourseType() == 6) {
                    cell6.setCellValue("缺课");
                } else if (classesNum.getCourseType() == 7) {
                    cell6.setCellValue("临时");
                }
            }
            sheet.setColumnWidth(5, 20 * 256);
            cell6.setCellStyle(cellStyle);

            Cell cell7 = row.createCell(6);
            cell7.setCellValue(classesNum.getStatus().getValue());
            sheet.setColumnWidth(6, 20 * 256);
            cell7.setCellStyle(cellStyle);

            Cell cell8 = row.createCell(7);
            cell8.setCellValue(classesNum.getBuckleClassHouse());
            sheet.setColumnWidth(7, 20 * 256);
            cell8.setCellStyle(cellStyle);

            Cell cell9 = row.createCell(8);
            cell9.setCellValue(classesNum.getBuckleClassMoney().toString());
            sheet.setColumnWidth(8, 20 * 256);
            cell9.setCellStyle(cellStyle);

            Cell cell10 = row.createCell(9);
            cell10.setCellValue(classesNum.getTeacherName());
            sheet.setColumnWidth(9, 20 * 256);
            cell10.setCellStyle(cellStyle);

            Cell cell11 = row.createCell(10);
            cell11.setCellValue(classesNum.getSchoolName());
            sheet.setColumnWidth(10, 20 * 256);
            cell11.setCellStyle(cellStyle);
        }

        String fileName = "课时汇总详情" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.GET_OK, "", "导出成功");
    }


    @ApiOperation("市场部列表导出")
    @GetMapping("/trackMarketExcel")
    public Result trackMarketExcel(@RequestParam Map<String, String> reMap, HttpServletResponse response) throws IOException {
        String name = reMap.get("name");
        String trackId = reMap.get("trackId");// 赛道id（暂时不需要）
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String classify = reMap.get("classify");//分类：分类：1是续班赛道，2是招生赛道
        Integer trackType = 1;
        if (StringUtils.isEmpty(classify)) {
            classify = "1";
        }

        QueryWrapper<TrackMarket> queryWrapper = new QueryWrapper<>();
        if (trackType == 1) {
            queryWrapper.like(StringUtils.isNotBlank(name), "track_market.name", name);
        }
        if (trackType == 2) {
            queryWrapper.like(StringUtils.isNotBlank(name), "track_market.team_name", name);
        }
        queryWrapper.eq("track_market.classify", classify);
        queryWrapper.eq("track_market.deleted", 0);
        queryWrapper.eq("track_detail.deleted", 0);
        queryWrapper.eq("track_market.track_type", trackType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "track_market.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "track_market.quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(trackId), "track_detail.track_id", trackId);
        queryWrapper.orderByDesc("track_market.id");
        List<TrackMarket> workingSchedule = trackMarketMapper.getTrackMarketDetails(queryWrapper);

        List<String> headList = new ArrayList<>();
        headList.add("市场部老师");
        headList.add("教师");
        headList.add("校区");
        headList.add("年级");
        headList.add("班型");
        headList.add("科目");

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("市场部");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引
        String lastGradeExcel = null; // 上一个班级名称
        int lastGradeNameRowIndex = 1; // 上一个班级姓名的数据行索引，初始化为1

        for (TrackMarket studentGradeExcel : workingSchedule) {
            Row row = sheet.createRow(rowIndex);

            Cell cell = row.createCell(0);
            cell.setCellValue(studentGradeExcel.getName());
            sheet.setColumnWidth(0, 20 * 256);
            cell.setCellStyle(cellStyle);

            Cell cell1 = row.createCell(1);
            cell1.setCellValue(studentGradeExcel.getTeacherName());
            sheet.setColumnWidth(1, 20 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(2);
            if (StringUtils.isNotBlank(studentGradeExcel.getSchoolIdStr())) {
                String schoolIdStr = studentGradeExcel.getSchoolIdStr();
                String[] schoolIds = schoolIdStr.split(",");
                StringBuffer schoolName = new StringBuffer();
                for (String schoolId : schoolIds) {
                    schoolName.append(iOrganizationService.getById(schoolId).getName());
                    schoolName.append("、");
                }
                cell2.setCellValue(schoolName.substring(0, schoolName.length() - 1));
            }
            sheet.setColumnWidth(2, 30 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(3);
            if (StringUtils.isNotBlank(studentGradeExcel.getYearClassIdStr())) {
                String yearClassStr = studentGradeExcel.getYearClassIdStr();
                String[] yearClassIds = yearClassStr.split(",");
                StringBuffer yearClassName = new StringBuffer();
                for (String yearClassId : yearClassIds) {
                    yearClassName.append(CommonUtil.getYearClassNameForId(Integer.valueOf(yearClassId)));
                    yearClassName.append("、");
                }
                cell3.setCellValue(yearClassName.substring(0, yearClassName.length() - 1));
            }
            sheet.setColumnWidth(3, 30 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(4);
            if (StringUtils.isNotBlank(studentGradeExcel.getClassTypeIdStr())) {
                String classTypeIdStr = studentGradeExcel.getClassTypeIdStr();
                String[] classTypeIds = classTypeIdStr.split(",");
                StringBuffer classTypeName = new StringBuffer();
                for (String classTypeId : classTypeIds) {
                    classTypeName.append(iCourseTypeService.getById(classTypeId).getName());
                    classTypeName.append("、");
                }
                cell4.setCellValue(classTypeName.substring(0, classTypeName.length() - 1));
            }
            sheet.setColumnWidth(4, 30 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(5);
            if (StringUtils.isNotBlank(studentGradeExcel.getSubjectsIdStr())) {
                String subjectsIdStr = studentGradeExcel.getSubjectsIdStr();
                String[] subjectsIds = subjectsIdStr.split(",");
                StringBuffer subjectsName = new StringBuffer();
                for (String subjectsId : subjectsIds) {
                    subjectsName.append(CommonUtil.getSubjectsNameForId(Integer.valueOf(subjectsId)));
                    subjectsName.append("、");
                }
                cell5.setCellValue(subjectsName.substring(0, subjectsName.length() - 1));
            }
            sheet.setColumnWidth(5, 30 * 256);
            cell5.setCellStyle(cellStyle);

            // 市场部老师合并逻辑
            if (lastGradeExcel != null && !studentGradeExcel.getName().equals(lastGradeExcel)) {
                if (rowIndex - lastGradeNameRowIndex > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, 0, 0));
                }
                lastGradeNameRowIndex = rowIndex; // 更新为当前数据行索引
            }
            lastGradeExcel = studentGradeExcel.getName();

            rowIndex++;
        }

        // 处理最后一个市场部老师的合并
        if (rowIndex - lastGradeNameRowIndex > 1) {
            sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, 0, 0));
        }

        String fileName = "市场部导出" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @ApiOperation("赛道列表导出")
    @GetMapping("/trackExcel")
    public Result trackExcel(@RequestParam Map<String, String> reMap, HttpServletResponse response) throws IOException {
        String name = reMap.get("name");
        String trackId = reMap.get("trackId");// 赛道id（暂时不需要）
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String classify = reMap.get("classify");//分类：分类：1是续班赛道，2是招生赛道
        Integer trackType = 1;
        if (StringUtils.isEmpty(classify)) {
            classify = "1";
        }

        QueryWrapper<TrackMarket> queryWrapper = new QueryWrapper<>();
        if (trackType == 1) {
            queryWrapper.like(StringUtils.isNotBlank(name), "track.name", name);
        }
        if (trackType == 2) {
            queryWrapper.like(StringUtils.isNotBlank(name), "track.team_name", name);
        }
        queryWrapper.eq("track.classify", classify);
        queryWrapper.eq("track.deleted", 0);
        queryWrapper.eq("track.deleted", 0);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "track.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "track.quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(trackId), "track_detail.track_id", trackId);
        queryWrapper.orderByDesc("track.type");
        queryWrapper.orderByAsc("track.sort");
        List<TrackMarket> workingSchedule = trackMarketMapper.getTrackDetails(queryWrapper);

        List<String> headList = new ArrayList<>();
        headList.add("赛道名称");
        headList.add("赛道类型");
        headList.add("赛道详情");

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("赛道详情");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引
        String lastGradeExcel = null; // 上一个班级名称
        int lastGradeNameRowIndex = 1; // 上一个班级姓名的数据行索引，初始化为1

        for (TrackMarket studentGradeExcel : workingSchedule) {
            Row row = sheet.createRow(rowIndex);

            Cell cell = row.createCell(0);
            cell.setCellValue(studentGradeExcel.getName());
            sheet.setColumnWidth(0, 20 * 256);
            cell.setCellStyle(cellStyle);

            Cell cell1 = row.createCell(1);
            if (studentGradeExcel.getType() != null) {
                if (studentGradeExcel.getType() == 1) {
                    cell1.setCellValue("个人");
                } else if (studentGradeExcel.getType() == 2) {
                    cell1.setCellValue("校区");
                }
            }
            sheet.setColumnWidth(1, 20 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(2);
            cell2.setCellValue(studentGradeExcel.getTeacherName());
            sheet.setColumnWidth(2, 20 * 256);
            cell2.setCellStyle(cellStyle);

            // 赛道名称合并逻辑
            if (lastGradeExcel != null && !studentGradeExcel.getName().equals(lastGradeExcel)) {
                if (rowIndex - lastGradeNameRowIndex > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, 0, 0));
                }
                lastGradeNameRowIndex = rowIndex; // 更新为当前数据行索引
            }
            lastGradeExcel = studentGradeExcel.getName();

            rowIndex++;
        }

        // 处理最后一个赛道名称的合并
        if (rowIndex - lastGradeNameRowIndex > 1) {
            sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, 0, 0));
        }

        String fileName = "赛道详情导出" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }

    @GetMapping("/gradePositionExcel")
    @ApiOperation("排班顺位列表导出")
    public Result gradePositionExcel(@RequestParam Map<String, String> reMap) throws IOException {
        Integer pageNum = -1;
        Integer pageSize = -1;
        Page<Grade> page = new Page<>(pageNum, pageSize);

        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String schoolId = reMap.get("schoolId");
        String yearClassId = reMap.get("yearClassId");
        String subjectsId = reMap.get("subjectsId");
        String teacherId = reMap.get("teacherId");
        String status = reMap.get("status");//0未满班 1满班
        String gradeId = reMap.get("gradeId");
        String isDescOrAsc = reMap.get("isDescOrAsc");// 0正序 1倒序

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(yearPart), "grade.year_part", yearPart);
        wrapper.eq(StringUtils.isNotBlank(quarterNum), "grade.quarter_num", quarterNum);
        wrapper.inSql(StringUtils.isNotBlank(schoolId), "grade.school_id", schoolId);
        wrapper.eq(StringUtils.isNotBlank(yearClassId), "grade.year_class_id", yearClassId);
        wrapper.eq(StringUtils.isNotBlank(subjectsId), "grade.subjects_id", subjectsId);
        wrapper.eq(StringUtils.isNotBlank(teacherId), "grade.teacher_id", teacherId);
        wrapper.eq("grade.lesson_type", 1);
        wrapper.inSql(StringUtils.isNotBlank(gradeId), "grade.id", gradeId);
        wrapper.eq("grade.deleted", 0);

        wrapper.groupBy("grade.id");

        if (StringUtils.isNotBlank(status)) {
            if (status.equals("0")) {
                wrapper.having("grade.full_count > student_count and grade.full_count <> 0");
            } else if (status.equals("1")) {
                wrapper.having("grade.full_count <= student_count and grade.full_count <> 0");
            } else if (status.equals("2")) {
                wrapper.having("grade.full_count = 0");
            }
        }

        if (StringUtils.isNotBlank(isDescOrAsc)) {
            if (isDescOrAsc.equals("0")) {
                wrapper.orderByAsc("position_num");
            } else if (isDescOrAsc.equals("1")) {
                wrapper.orderByDesc("position_num");
            }
        }

        iGradeService.getGradePosition(page, wrapper);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("排班顺位");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        CellStyle cellStyle1 = workbook.createCellStyle();
        cellStyle1.setFont(headerFont);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle1.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
        cellStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        CellStyle cellStyle2 = workbook.createCellStyle();
        cellStyle2.setFont(headerFont);
        cellStyle2.setAlignment(HorizontalAlignment.CENTER);
        cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle2.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        CellStyle cellStyle3 = workbook.createCellStyle();
        cellStyle3.setFont(headerFont);
        cellStyle3.setAlignment(HorizontalAlignment.CENTER);
        cellStyle3.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle3.setFillForegroundColor(IndexedColors.RED.getIndex());
        cellStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        List<String> headList = new ArrayList<>();
        headList.add("班级");
        headList.add("班主任");
        headList.add("班型");
        headList.add("顺位");
        headList.add("满班人数");
        headList.add("已排人数");
        headList.add("状态");
        headList.add("分数区间");
        headList.add("科目");
        headList.add("年级");
        headList.add("校区");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        int rowIndex = 1;// 数据行起始索引

        for (Grade grade : page.getRecords()) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(grade.getName());
            sheet.setColumnWidth(0, 30 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(grade.getTeacherName());
            sheet.setColumnWidth(1, 20 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(iCourseTypeService.getNameForId(grade.getCourseTypeId()));
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(3);
            cell4.setCellValue(grade.getPositionNum());
            sheet.setColumnWidth(3, 20 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(4);
            cell5.setCellValue(grade.getFullCount());
            sheet.setColumnWidth(4, 20 * 256);
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(5);
            cell6.setCellValue(grade.getStudentCount());
            sheet.setColumnWidth(5, 20 * 256);
            cell6.setCellStyle(cellStyle);

            Cell cell7 = row.createCell(6);
            if (grade.getStudentCount() >= grade.getFullCount() && grade.getFullCount() != 0) {
                cell7.setCellValue("已满班");
                cell7.setCellStyle(cellStyle1);
            } else if (grade.getStudentCount() < grade.getFullCount() && grade.getFullCount() != 0) {
                cell7.setCellValue("未满班");
                cell7.setCellStyle(cellStyle2);
            } else {
                cell7.setCellValue("未设置");
                cell7.setCellStyle(cellStyle3);
            }
            sheet.setColumnWidth(6, 20 * 256);

            Cell cell8 = row.createCell(7);
            cell8.setCellValue(grade.getStartScore() + " - " + grade.getEndScore());
            sheet.setColumnWidth(7, 25 * 256);
            cell8.setCellStyle(cellStyle);

            Cell cell9 = row.createCell(8);
            cell9.setCellValue(CommonUtil.getSubjectsNameForId(Math.toIntExact(grade.getSubjectsId())));
            sheet.setColumnWidth(8, 20 * 256);
            cell9.setCellStyle(cellStyle);

            Cell cell10 = row.createCell(9);
            cell10.setCellValue(grade.getYearClassId().getValue());
            sheet.setColumnWidth(9, 20 * 256);
            cell10.setCellStyle(cellStyle);

            Cell cell11 = row.createCell(10);
            cell11.setCellValue(iOrganizationService.getSchoolName(grade.getSchoolId()));
            sheet.setColumnWidth(10, 25 * 256);
            cell11.setCellStyle(cellStyle);
        }

        String fileName = "排班顺位导出" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.GET_OK, "", Code.GET_OK_MSG);
    }

    @GetMapping("/gradeLayerExcel")
    @ApiOperation("班级分层导出")
    public Result searchGradeLayer(@RequestParam Map reMap) throws IOException {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<GradeLayer> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String classTypeId = (String) reMap.get("classTypeId");
        String subjectsId = (String) reMap.get("subjectsId");
        String yearClassId = (String) reMap.get("yearClassId");
        String lessonType = (String) reMap.get("lessonType");
        String startScore = (String) reMap.get("startScore");
        String endScore = (String) reMap.get("endScore");
        String ids = (String) reMap.get("ids");

        QueryWrapper<GradeLayer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(classTypeId), "class_type_id", classTypeId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);

        String[] yearClassIdStr = yearClassId.split(","); // 拆分成数组
        StringBuilder condition = new StringBuilder();
        for (int i = 0; i < yearClassIdStr.length; i++) {
            if (i > 0) {
                condition.append(" OR ");
            }
            condition.append("FIND_IN_SET(").append(yearClassIdStr[i]).append(", year_class_id_str)");
        }
        if (StringUtils.isNotBlank(yearClassId)) {
            queryWrapper.apply("(" + condition + ")");
        }

        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.ge(StringUtils.isNotBlank(startScore), "start_score", startScore);
        queryWrapper.le(StringUtils.isNotBlank(endScore), "end_score", endScore);
        queryWrapper.inSql(StringUtils.isNotBlank(ids), "id", ids);

        iGradeLayerService.page(iPage, queryWrapper);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("班级分层");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        headList.add("年份");
        headList.add("学期");
        headList.add("科目");
        headList.add("学段");
        headList.add("年级");
        headList.add("班型");
        headList.add("分数区间");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        int rowIndex = 1;// 数据行起始索引

        for (GradeLayer gradeLayer : iPage.getRecords()) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(gradeLayer.getYearPart());
            sheet.setColumnWidth(0, 15 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(CommonUtil.getQuarterNameForId(gradeLayer.getQuarterNum()));
            sheet.setColumnWidth(1, 15 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(CommonUtil.getSubjectsNameForId(Math.toIntExact(gradeLayer.getSubjectsId())));
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(3);
            cell4.setCellValue(CommonUtil.getGradeSectionNameForId(gradeLayer.getGradeSection()));
            sheet.setColumnWidth(3, 20 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(4);
            cell5.setCellValue(gradeLayer.getYearClassNameStr());
            sheet.setColumnWidth(4, 50 * 256);
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(5);
            cell6.setCellValue(iCourseTypeService.getNameForId(gradeLayer.getClassTypeId()));
            sheet.setColumnWidth(5, 20 * 256);
            cell6.setCellStyle(cellStyle);

            Cell cell7 = row.createCell(6);
            cell7.setCellValue(gradeLayer.getStartScore() + " - " + gradeLayer.getEndScore());
            sheet.setColumnWidth(6, 30 * 256);
            cell7.setCellStyle(cellStyle);
        }

        String fileName = "班级分层导出" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();


        return new Result(Code.GET_OK, "", Code.GET_OK_MSG);
    }

    @GetMapping("/floatExcel")
    @ApiOperation("浮动排班列表导出")
    public Result floatList(@RequestParam Map<String, String> reMap) throws IOException {
        Page<Grade> page = new Page<>(-1, -1);

        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String schoolId = reMap.get("schoolId");
        String yearClassId = reMap.get("yearClassId");
        String subjectsId = reMap.get("subjectsId");
        String teacherId = reMap.get("teacherId");
        String gradeId = reMap.get("gradeId");
        String classRoomId = reMap.get("classRoomId");
        String courseTypeId = reMap.get("courseTypeId");
        String isDescOrAsc = reMap.get("isDescOrAsc");// 0正序 1倒序
        String isFieldToSc = reMap.get("isFieldToSc");// 要排序的字段
        String iSeal = reMap.get("iSeal");// 1为封班，0未不封班
        String startDate = reMap.get("startDate");// 开始时间
        String endDate = reMap.get("endDate");// 结束时间

        iGradeService.getGradeFloatList(page, yearPart, quarterNum, yearClassId, courseTypeId, subjectsId, schoolId, teacherId, classRoomId, gradeId, isDescOrAsc, isFieldToSc, iSeal, startDate, endDate);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("浮动排班");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        List<String> headList = new ArrayList<>();
        headList.add("班级名称");
        headList.add("班型");
        headList.add("教师");
        headList.add("上课时间");
        headList.add("上课时段");
        headList.add("教室");
        headList.add("满班人数");
        headList.add("新生");
        headList.add("老生");
        headList.add("已排");
        headList.add("名额剩余");
        headList.add("开班校区");

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        int rowIndex = 1;// 数据行起始索引

        for (Grade grade : page.getRecords()) {
            Row row = sheet.createRow(rowIndex++);

            Cell cell1 = row.createCell(0);
            cell1.setCellValue(grade.getName());
            sheet.setColumnWidth(0, 30 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(1);
            cell2.setCellValue(grade.getClassTypeName());
            sheet.setColumnWidth(1, 20 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(2);
            cell3.setCellValue(grade.getTeacherName());
            sheet.setColumnWidth(2, 20 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(3);
            if (grade.getIsVacation() != null) {
                if (grade.getIsVacation() == 0) {
                    cell4.setCellValue(CommonUtil.getWeekForId(Integer.valueOf(grade.getWeekDates())));
                } else if (grade.getIsVacation() == 1) {
                    cell4.setCellValue(grade.getWeekDates());
                }
            }
            sheet.setColumnWidth(3, 20 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(4);
            cell5.setCellValue(grade.getTimeStart() + " ~ " + grade.getTimeEnd());
            sheet.setColumnWidth(4, 30 * 256);
            cell5.setCellStyle(cellStyle);

            Cell cell6 = row.createCell(5);
            cell6.setCellValue(grade.getClassRoomName());
            sheet.setColumnWidth(5, 20 * 256);
            cell6.setCellStyle(cellStyle);

            Cell cell7 = row.createCell(6);
            cell7.setCellValue(grade.getFullCount());
            sheet.setColumnWidth(6, 15 * 256);
            cell7.setCellStyle(cellStyle);

            Cell cell8 = row.createCell(7);
            cell8.setCellValue(grade.getNewStudentCount());
            sheet.setColumnWidth(7, 15 * 256);
            cell8.setCellStyle(cellStyle);

            Cell cell9 = row.createCell(8);
            cell9.setCellValue(grade.getOldStudentCount());
            sheet.setColumnWidth(8, 15 * 256);
            cell9.setCellStyle(cellStyle);

            Cell cell10 = row.createCell(9);
            cell10.setCellValue(grade.getStudentCount());
            sheet.setColumnWidth(9, 15 * 256);
            cell10.setCellStyle(cellStyle);

            Cell cell11 = row.createCell(10);
            cell11.setCellValue(grade.getResidueCount());
            sheet.setColumnWidth(10, 15 * 256);
            cell11.setCellStyle(cellStyle);

            Cell cell12 = row.createCell(11);
            cell12.setCellValue(grade.getSchoolName());
            sheet.setColumnWidth(11, 25 * 256);
            cell12.setCellStyle(cellStyle);
        }

        String fileName = "浮动排班导出" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.GET_OK, "", Code.GET_OK_MSG);
    }

    @ApiOperation("排班学员账号密码导出")
    @GetMapping("/gradeAndStudentAccountExcel")
    public Result gradeAndStudentAccountExcel(@RequestParam Map<String, String> reMap, HttpServletResponse response) throws IOException {
        String schoolIdList = reMap.get("schoolIdList");
        String classRoomIdList = reMap.get("classRoomIdList");
        String courseIdList = reMap.get("courseIdList");
        String gradeIdList = reMap.get("gradeIdList");
        String yearClassIdList = reMap.get("yearClassIdList");
        String isCheckHouse = reMap.get("isCheckHouse");
        String lessonType = StringUtils.isEmpty(reMap.get("lessonType")) ? "1" : reMap.get("lessonType");
        String name = reMap.get("name");
        String subjectsId = reMap.get("subjectsId");
        String status = reMap.get("status");
        String teacherId = reMap.get("teacherId");
        String yearPart = reMap.get("yearPart");
        String quarterNumList = reMap.get("quarterNumList");

        List<StudentGradeExcel> workingSchedule = iGradeService.workingSchedulAccount(schoolIdList, name, yearClassIdList, subjectsId, status, classRoomIdList, courseIdList, yearPart, quarterNumList, teacherId, isCheckHouse, lessonType, gradeIdList);

        List<String> headList = new ArrayList<>();
        headList.add("班级名称");
        headList.add("开班校区");
        headList.add("班型");
        headList.add("学员姓名");
        headList.add("账号");
        headList.add("密码");

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("排班学员账号密码表");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引
        String lastGradeExcel = null; // 上一个班级名称
        int lastGradeNameRowIndex = 1; // 上一个班级姓名的数据行索引，初始化为1

        for (StudentGradeExcel studentGradeExcel : workingSchedule) {
            Row row = sheet.createRow(rowIndex);

            Cell cell = row.createCell(0);
            cell.setCellValue(studentGradeExcel.getGradeName());
            sheet.setColumnWidth(0, 30 * 256);
            cell.setCellStyle(cellStyle);

            Cell cell1 = row.createCell(1);
            cell1.setCellValue(studentGradeExcel.getOpenClassSchoolName());
            sheet.setColumnWidth(1, 20 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(2);
            cell2.setCellValue(studentGradeExcel.getClassTypeName());
            sheet.setColumnWidth(2, 20 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(3);
            cell3.setCellValue(studentGradeExcel.getStudentName());
            sheet.setColumnWidth(3, 15 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(4);
            cell4.setCellValue(studentGradeExcel.getAccount());
            sheet.setColumnWidth(4, 35 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(5);
            cell5.setCellValue(studentGradeExcel.getPwd());
            sheet.setColumnWidth(5, 35 * 256);
            cell5.setCellStyle(cellStyle);

            // 班级名称~班型合并逻辑
            if (lastGradeExcel != null && !studentGradeExcel.getGradeName().equals(lastGradeExcel)) {
                if (rowIndex - lastGradeNameRowIndex > 1) {
                    for (int j = 0; j <= 2; j++) {
                        sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, j, j));
                    }
                }
                lastGradeNameRowIndex = rowIndex; // 更新为当前数据行索引
            }
            lastGradeExcel = studentGradeExcel.getGradeName();
            rowIndex++;
        }

        // 处理最后一个班级的合并
        if (rowIndex - lastGradeNameRowIndex > 1) {
            for (int j = 0; j <= 2; j++) {
                sheet.addMergedRegion(new CellRangeAddress(lastGradeNameRowIndex, rowIndex - 1, j, j));
            }
        }

        String fileName = "排班学员账号密码表" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.OK, null, "导出成功");
    }


    /**
     * 临时排班导出
     */
    @GetMapping("/getTemporaryClassExcel")
    public Result getTemporaryClass(@RequestParam(value = "courseType", defaultValue = "9") Integer courseType,
                                    @RequestParam(value = "yearPart", required = false) String yearPart,
                                    @RequestParam(value = "quarterNum", required = false) String quarterNum,
                                    @RequestParam(value = "schoolId", required = false) String schoolId,
                                    @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                    @RequestParam(value = "startDate", defaultValue = "") String startDate,
                                    @RequestParam(value = "endDate", defaultValue = "") String endDate,
                                    @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
                                    @RequestParam(value = "courseId", defaultValue = "") String courseId,
                                    @RequestParam(value = "studentName", defaultValue = "") String studentName) throws IOException {

        IPage<RepairCourse> iPage = new Page<>(-1, -1);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("t1.deleted", 0);
        queryWrapper.eq("course_type", courseType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "t1.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "t1.quarter", quarterNum);
        queryWrapper.like(StringUtils.isNotBlank(studentName), "t4.`name`", studentName);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "t1.teacher_id", teacherId);
        queryWrapper.inSql(StringUtils.isNotBlank(schoolId), "t1.school_id", schoolId);
        queryWrapper.inSql(StringUtils.isNotBlank(courseId), "t3.id", courseId);
        queryWrapper.inSql(StringUtils.isNotBlank(subjectsId), "t1.subjects_id", subjectsId);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            queryWrapper.between("school_date", startDate, endDate);
        }

        iRepairCourseService.getTemporaryClass(iPage, queryWrapper);

        List<String> headList = new ArrayList<>();
        headList.add("学员姓名");
        headList.add("上课日期");
        headList.add("上课时段");
        headList.add("班级");
        headList.add("所属课程");
        headList.add("上课教师");
//        headList.add("是否过期");

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("临时排班记录");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 11);
        headerCellStyle.setFont(headerFont);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Row headerRow = sheet.createRow(0);
        sheet.createFreezePane(0, 1);// 冻结首行

        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
        }

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(headerFont);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        int rowIndex = 1; // 数据行起始索引

        for (RepairCourse repairCourse : iPage.getRecords()) {
            Row row = sheet.createRow(rowIndex);

            Cell cell = row.createCell(0);
            cell.setCellValue(repairCourse.getStudentName());
            sheet.setColumnWidth(0, 30 * 256);
            cell.setCellStyle(cellStyle);

            Cell cell1 = row.createCell(1);
            cell1.setCellValue(String.valueOf(repairCourse.getSchoolDate()));
            sheet.setColumnWidth(1, 20 * 256);
            cell1.setCellStyle(cellStyle);

            Cell cell2 = row.createCell(2);
            cell2.setCellValue(repairCourse.getTimeStart() + " - " + repairCourse.getTimeEnd());
            sheet.setColumnWidth(2, 20 * 256);
            cell2.setCellStyle(cellStyle);

            Cell cell3 = row.createCell(3);
            cell3.setCellValue(repairCourse.getGradeName());
            sheet.setColumnWidth(3, 15 * 256);
            cell3.setCellStyle(cellStyle);

            Cell cell4 = row.createCell(4);
            cell4.setCellValue(repairCourse.getCourseName());
            sheet.setColumnWidth(4, 35 * 256);
            cell4.setCellStyle(cellStyle);

            Cell cell5 = row.createCell(5);
            cell5.setCellValue(repairCourse.getTeacherName());
            sheet.setColumnWidth(5, 35 * 256);
            cell5.setCellStyle(cellStyle);

            // 是否过期
//            Cell cell6 = row.createCell(6);
//            if (repairCourse.getEndDateTime().isBefore(LocalDateTime.now())) {
//                cell6.setCellValue("已过期");
//            } else {
//                cell6.setCellValue("未过期");
//            }
//            sheet.setColumnWidth(6, 35 * 256);
//            cell6.setCellStyle(cellStyle);

            rowIndex++;
        }

        String fileName = "临时排班记录" + ".xls";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/zip");//设置为zip格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();


        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 批量导出课程表
     */
    @GetMapping("/timetableExcel")
    @ApiOperation("班级列表中的课程表")
    public Result timetableByGradeIdExcel(@RequestParam(value = "yearPart", required = false) Integer yearPart,
                                          @RequestParam(value = "quarterNum", required = false) Integer quarterNum,
                                          @RequestParam(value = "gradeId", required = false) String gradeId,
                                          @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                          @RequestParam(value = "schoolId", required = false) String schoolId,
                                          @RequestParam(value = "classRoomIdList", required = false) String classRoomIdList,
                                          @RequestParam(value = "courseIdList", required = false) String courseIdList,
                                          @RequestParam(value = "yearClassIdList", required = false) String yearClassIdList,
                                          @RequestParam(value = "name", required = false) String name,
                                          @RequestParam(value = "teacherId", required = false) String teacherId
    ) throws IOException {
        Page<Grade> page = new Page<>(-1, -1);

        Integer status = 1;// 根据年份学期判断是否只查询在读学员
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null || quarterNum == null) {
            yearPart = quarterNow.getYearPart();
            quarterNum = quarterNow.getNum();
        }
        if (quarterNow != null) {
            if (!yearPart.equals(quarterNow.getYearPart()) || !quarterNum.equals(quarterNow.getNum())) {
                status = 0;
            }
        }

        iGradeService.timetableByGradeIdList(page, yearPart, quarterNum, gradeId, String.valueOf(subjectsId), schoolId, classRoomIdList, courseIdList, yearClassIdList, name, teacherId);

        // 首行加筛选框
        CellRangeAddress cellRangeAddress = CellRangeAddress.valueOf("A1:G1");
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(yearPart + "年" + CommonUtil.getQuarterNameForId(quarterNum) + "课程表");
        CellStyle headerCellStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();// 创建字体对象
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 16);
        headerCellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
        headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        Row headerRow = sheet.createRow(0);
        headerRow.setHeightInPoints(30);
        sheet.createFreezePane(0, 1);// 冻结首行
        headerCellStyle.setFont(headerFont);
        sheet.setAutoFilter(cellRangeAddress);

        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 13);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);//设置为自动换行

        List<String> headList = new ArrayList<>();
        headList.add("学员姓名");
        headList.add("英语精品课");
        headList.add("英语智能课");
        headList.add("数学精品课");
        headList.add("数学刷题班");
        headList.add("物理精品课");
        headList.add("物理刷题班");

        Map<String, Integer> subjectLessonTypeToIndexMap = new HashMap<>();
        for (int i = 0; i < headList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headList.get(i));
            cell.setCellStyle(headerCellStyle);
            sheet.setColumnWidth(i, 41 * 256);
            subjectLessonTypeToIndexMap.put(headList.get(i), i);
        }

        int rowIndex = 1;// 数据行起始索引
        Long currentStudentId = null;

        for (Grade grade : page.getRecords()) {
            String key = CommonUtil.buildSubjectLessonTypeKey(grade.getSubjectsId(), grade.getLessonType());
            Integer columnIndex = subjectLessonTypeToIndexMap.get(key);

            if (columnIndex != null) {
                if (!grade.getStudentId().equals(currentStudentId)) {
                    rowIndex++;
                    currentStudentId = grade.getStudentId();
                }

                Row row = sheet.getRow(rowIndex);
                if (row == null) {
                    row = sheet.createRow(rowIndex);
                }

                Cell cell1 = row.getCell(0);
                if (cell1 == null) {
                    cell1 = row.createCell(0);
                }
                cell1.setCellValue(grade.getStudentName());
                sheet.setColumnWidth(0, 21 * 256);
                cell1.setCellStyle(cellStyle);

                // 填充课程时间（班级名称 + 星期 + 时间段）
                Cell cell2 = row.getCell(columnIndex);
                if (cell2 == null) {
                    cell2 = row.createCell(columnIndex);
                }

                // 检查单元格是否已经有内容，如果有则拼接，没有则直接设置
                String existingContent = cell2.getStringCellValue();
                StringBuilder schoolTimeSb = new StringBuilder(existingContent);

                if (StringUtils.isNotBlank(grade.getWeekDates())) {
                    String[] weekArr = grade.getWeekDates().split(",");
                    for (String weekDay : weekArr) {
                        if (schoolTimeSb.length() > 0) {
                            schoolTimeSb.append("\r\n"); // 添加换行符分隔不同的课程时间
                        }
                        schoolTimeSb.append(grade.getName());
                        schoolTimeSb.append("\r\n");
                        try {
                            if (weekDay.matches("\\d+")) {
                                weekDay = CommonUtil.getWeekForId(Integer.valueOf(weekDay));
                            } else {
                                if (weekDay.equals("A") || weekDay.equals("B")) {
                                    weekDay = weekDay + "天";
                                }
                            }
                        } catch (Exception e) {
                            System.err.println(e.getMessage());
                        }
                        schoolTimeSb.append(weekDay);
                        if (StringUtils.isNotBlank(grade.getTimeStart()) && StringUtils.isNotBlank(grade.getTimeEnd())) {
                            schoolTimeSb.append("  ").append(grade.getTimeStart()).append(" - ").append(grade.getTimeEnd());
                        }
                    }
                }

                cell2.setCellValue(String.valueOf(schoolTimeSb));
                cell2.setCellStyle(cellStyle);
            }
        }

        // 删除第二行空行
        sheet.shiftRows(2, rowIndex + 1, -1);

        String fileName = yearPart + "年" + CommonUtil.getQuarterNameForId(quarterNum) + "课程表" + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

//        response.setContentType("application/zip");//设置为zip格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置为excel格式
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);//设置响应头

        // 获取响应输出流
        OutputStream outputStream = response.getOutputStream();

        // 将工作簿写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();

        // 刷新输出流
        outputStream.flush();

        //关闭输出流
        outputStream.close();

        return new Result(Code.GET_OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }

}
